1

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 year, 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?

1

3 Answers 3

2

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');
Sign up to request clarification or add additional context in comments.

1 Comment

This was really helpful as well. If only I could select two correct answers!
1

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.

Comments

1

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>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.