I need a date object that has a time of 12:00:00am for the current day (meaning no seconds). I am converting that to that to the number of seconds and passing it in another function. It is eventually used for a report filter using date = "someDateHere' off the database, and the hanging seconds in the field are screwing up the report.
I'm not sure what to put in the second parameter in the time function - leaving it blank will use the current time, which is what I do not want. I can't find examples or anything in the php doc. If there is another function that will do the job, I am open to suggestions. This should be simple, but it is alluding me.
date_default_timezone_set('America/Detroit');
$now = date("Y-m-d 0:0:0");
echo $now . '<br/>';
$now = time($now,0);
echo $now . '<br/>';
Thanks in advance.
edit: Please note: I need to convert that date object to seconds. That is where the timestamp is screwing me up with strtotime function and time function. Even though I am passing it a dateobject without a timestamp, converting it into seconds not-so-conveniently is inserting the timestamp as the second parameter which defaults to the current time.
There are lots of available options here, since PHP accepts a wide variety of time formats.
$midnight = strtotime('midnight');
$midnight = strtotime('today');
$midnight = strtotime('12:00am');
$midnight = strtotime('00:00');
// etc.
Or in DateTime form:
$midnight = new DateTime('midnight');
$midnight = new DateTime('today');
$midnight = new DateTime('12:00am');
$midnight = new DateTime('00:00');
// etc.
See time formats and relative formats in the manual for a complete list of formats with descriptions.
Oh, I'd stop using those functions entirely, and start taking advantage of the DateTime class!
$date = new DateTime("now", new DateTimeZone("America/Detroit"));
echo $date->format("Y-m-d");
http://php.net/manual/en/class.datetime.php
time() takes no arguments. what you're doing is pointless. why not just strtotime(date('Y-m-d')) to get the unix timestamp for midnight?
i think mktime() is just what you need http://www.php.net/manual/en/function.mktime.php
<?php
// Set the default timezone to use. Available as of PHP 5.1
date_default_timezone_set('UTC');
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
// Prints something like: 2006-04-05T01:02:03+00:00
echo date('c', mktime(1, 2, 3, 4, 5, 2006));
?>
Related
My understanding is that datetimes in php are represented as the number of milliseconds after a certain date (some time in 1960 I think?). How to I construct a datetime that represents the earliest allowable date in php? An example possible syntax would be:
$date = new DateTime(0);
but this doesn't work. Is there some other way to do this?
Thanks for any input.
You're pretty close
$date = (new DateTime())->setTimestamp(0);
Will give January 1st, 1970
I think the smallest and largest dates that the DateTime object will accept are as follows (on a 64 bit machine as of PHP 7.4, demonstrated using PHPUnit). This can be useful in providing default mins and maxes on a date validator for both DateTime as well as Carbon. This answer is also posted in the user contributed notes of the PHP manual page for DateTime::__construct().
If you want to get very precise about it, modify the code below to account for time and timezone.
// smallest date
$input = '-9999-01-01';
$dt = new \DateTime($input);
self::assertEquals($input, $dt->format('Y-m-d'));
$input = '-10000-12-31';
$dt = new \DateTime($input);
self::assertEquals('2000-12-31', $dt->format('Y-m-d'));
// largest date
$input = '9999-12-31';
$dt = new \DateTime($input);
self::assertEquals($input, $dt->format('Y-m-d'));
$input = '10000-01-01';
$dt = new \DateTime($input);
self::assertEquals('2000-01-01', $dt->format('Y-m-d'));
echo date('d-m-Y', 0); // outputs: 01-01-1970
epoch 0 gives the unix timestamp 01-01-1970 or 00:00:00 UTC on January 1st 1970.
I' am trying to convert the date of next 7 days into timestamp so that I can compare against my date timestamp in database to get some results.
This function is used to get the next 7 days from today
$next_date = date("d/m/Y", strtotime("7 day"))
Output
30/04/2014
Now I' am again running strtotime() on $next_date variable who holds the next 7days and converting to timestamp.
echo strtotime($next_date);
This is not working. I followed this stackoverflow answer and few others.
As an alternative suggestion you could look at PHP's internal DateTime() and DateInterval() classes. It makes it a bit easier to convert between formats and do date/time addition and subtraction imho. DateInterval requires at least PHP version 5.3.
An example:
// create a current DateTime
$currDate = new DateTime();
// copy the current DateTime and
// add an interval of 7 days
$nextDate = clone $currDate;
$nextDate->add(new DateInterval('P7D'));
// both objects are easily converted to timestamps
echo $currDate->getTimestamp(); // e.g: 1398296728
echo $nextDate->getTimestamp(); // e.g: 1398901528
// and both can be easily formatted in other formats
echo $currDate->format('d/m/Y'); // e.g: 24/04/2014
echo $nextDate->format('d/m/Y'); // e.g: 01/05/2014
EDIT
For completeness, here's another example of how you can add seven days to a DateTime object:
$now = new DateTimeImmutable();
$then = $now->modify('+7 days');
var_dump($now->format('Y-m-d'), $then->format('Y-m-d'));
Yields:
string(10) "2016-05-24"
string(10) "2016-05-31"
You can also use DateTime - the difference in this use case is that DateTime::modify() will modify the instance $now where DateTimeImmutable::modify() will return a new DateTimeImmutable object - so if you need to create a new object whilst retaining the old one, it's probably the most succinct approach.
Hope this helps :)
http://www.php.net/manual/en/datetime.construct.php
http://www.php.net/manual/en/dateinterval.construct.php
Just store the value from strtotime first?
$timestamp_in_7_days = strtotime('7 day');
$next_date = date('d/m/Y', $timestamp_in_7_days);
There is no need to throw the time back and forth between unix timestamp and date-format.
I have a PHP DateTime object with microseconds created as follows:
$time = microtime(true);
$microseconds = sprintf('%06d', ($time - floor($time)) * 1000000);
$dt = new DateTime(date('Y-m-d H:i:s.' . $microseconds, $time));
How can I modify the microseconds value of $dt, without creating a completely new DateTime instance?
You can't.
There are three methods that can modify the value of a DateTime instance: add, sub and modify. We can rule out add and sub immediately because they work in terms of a DateInterval which does not have sub-second precision.
modify accepts a string in one of the standard recognized formats. Of those formats, only the relative ones are of interest here because the other ones work in an absolute manner; and there is no relative format that allows tweaking the msec part (that unit is not recognized).
as of PHP 7.1
DateTime::setTime() supports microseconds.
This seems to have been available since 7.1.0-rc4
$dt = new DateTime('2020-01-01 0:00');
$dt->modify('+500 ms'); // Milliseconds.
$dt->modify('+123456 usec'); // Microseconds.
$dt->modify('+123456 microseconds'); // This works too.
It's mentioned here in the manual.
Manually creating a DateTime object with micro seconds:
$d = new DateTime("15-07-2014 18:30:00.111111");
Getting a DateTime object of the current time with microseconds:
$d = date_format(new DateTime(),'d-m-Y H:i:s').substr((string)microtime(), 1, 8);
Difference between two DateTime objects in microseconds (e.g. returns: 2.218939)
//Returns the difference, in seconds, between two datetime objects including
//the microseconds:
function mdiff($date1, $date2){
$date1sec = strtotime($date1->format('d-m-Y H:i:s.u'));
$date2sec = strtotime($date2->format('d-m-Y H:i:s.u'));
//Absolute val of Date 1 in seconds from (EPOCH Time) - Date 2 in seconds from (EPOCH Time)
$secdiff = abs($date1sec-$date2sec);
//Creates variables for the microseconds of date1 and date2
$micro1 = $date1->format("u");
$micro2 = $date2->format("u");
if (($date1sec<$date2sec && $micro1>$micro2)||($date1sec>$date2sec && $micro1<$micro2)){
$microdiff = abs(1000000 - abs($micro1-$micro2));
$secdiff = $secdiff - 1;
} else {
$microdiff = abs($micro1 - $micro2);
}
//Creates the variable that will hold the seconds (?):
$difference = $secdiff.".".$microdiff;
return $difference;
}
Essentially it finds the difference for the DateTime Objects using strtotime and then adding the extra microseconds on.
Do you need me to create add and sub?
i had a similar problem and ended up having to wrap the whole thing
https://gist.github.com/chandeeland/9817516
For the people only in need to zero-out microseconds (I had to because of database layer) here's the snippet I ended up using:
$format = "Y-m-d H:i:s e";
$now = (new \DateTime())->format($format);
$dateTime = \DateTime::createFromFormat($format, $now);
Note that using $format = 'c', ISO 8601, will not work, as explained here (https://stackoverflow.com/a/10478469/8119317).
I have a year (2002) and I'm trying to get it into the following format:
2002-00-00T00:00:00
I tried various iterations, the last of which was this:
$testdate = DateTime::createFromFormat(DateTime::ISO8601, date("c"))
echo date_format($testdate, '2002');
But, even if I come close, it always seems to add +00:00 to the end of it...
The 'c' format in PHP always appends the timezone offset. You can't avoid that. But you can build the date yourself from components:
date('Y-m-d\TH:i:s', $testdate);
Best way is to use constants (PHP 5 >= 5.5.0, PHP 7)
date(DATE_ISO8601, $timeToChange);
Docs:
http://php.net/manual/en/class.datetimeinterface.php#datetime.constants.types
The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:
// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z
// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z
// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z
//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z
Previous published: https://stackoverflow.com/a/61796705/5898408
date('Y-m-d\TH:i:s\Z', time() - date('Z'));
What is easiest way to display the current time in PST (West Coast) time using PHP?
Well, the easiest might be:
date_default_timezone_set('America/Los_Angeles');
echo date('Y-m-d');
Take a look at supported timezones to find one suitable for your needs.
Let's try a solution that uses PHP's modern date handling. This example requires PHP 5.2 or better.
// Right now it's about four minutes before 1 PM, PST.
$pst = new DateTimeZone('America/Los_Angeles');
$three_hours_ago = new DateTime('-3 hours', $pst); // first argument uses strtotime parsing
echo $three_hours_ago->format('Y-m-d H:i:s'); // "2010-06-15 09:56:36"
If you are using or have access to Carbon you could do this:
$timezone = 'America/Los_Angeles';
$now = Carbon::now()->tz($timezone)->toDateTimeString();
echo $now;
.
echo date('r');
putenv('TZ=PST');
echo date('r');
To convert a date/time between timezones:
include ("Date.php");
$d = new Date("2010-06-21 10:59:27"); // initialize object
$d->setTZByID("GMT"); // set local time zone
$d->convertTZByID("PST"); // convert to foreign time zone
echo $d->format("%A, %d %B %Y %T"); // retrieve converted date/time