I'm trying to do some basic date and timestamp operations in PHP and have been getting unexpected results. I'm trying to get a timestamp with just the yea开发者_StackOverflow社区r, month, and day of the month (i.e. the timestamp of a date at 12:00 A.M.) of the existing timestamp $startDate
. It was changing the date as well, though, as can be seen in the following code.
$startDateString = date("Y-M-j", $startDate);
$startDateTimestamp = strtotime($startDateString);
echo "$startDate == $startDateTimestamp ?<br>";
echo date("Y-M-j", $startDate)." == ".date("Y-M-j", $startDateTimestamp)." ?<br>";
This gives me the following output:
1299299589 == 1298952000 ?
2011-Mar-4 == 2011-Feb-28 ?
While I wouldn't expect the timestamps to be the same (as $startDate
is not necessarily at 12:00 A.M.), I can't see how the calendar dates aren't the same. What am I doing wrong?
From the strtotime documentation:
A date/time string. Valid formats are explained in Date and Time Formats.
As for the problem you are trying to solve, you can pass other things to strtotime, like relative formats.
strtotime('midnight', $startDate);
As an example, to echo midnight (you can also use today if midnight is confusing) of the current time:
echo date('Y-m-d H:i:s', strtotime('midnight'));
Both 'today' and 'midnight'
The time is set to 00:00:00
Of course I am a big fan of the DateTime object.
$date = new DateTime($startDate);
$date->modify('midnight');
echo $date->format('Y-m-d H:i:s');
After some short tests, I noticed that strtotime()
is unable to parse the format Y-M-j
properly. To fix this, use a standard format, such as RFC822 date time format, ISO-8601 date time format or use j-M-Y
instead.
I usually use the "Y-m-d" format for similar tasks and that works:
$startDateString = date("Y-m-d", $startDate);
$startDateTimestamp = strtotime($startDateString);
echo "$startDate == $startDateTimestamp ?<br>";
echo date("Y-m-d", $startDate)." == ".date("Y-m-d", $startDateTimestamp)." ?<br>";
精彩评论