Tuesday 17 July 2018

PHP date() Function Showing Date from 1970

PHP date() Function Showing Date from 1970

I’ve lost count of the amount of times I’ve used the PHP date() function and wondered why it’s returning a date from 1970 so I wanted to share with you the most common reason/mistake I’ve found for causing this in the event that you are facing the same problem.
The Solution
The date() function can accept two parameters; the format of the required date and an optional UNIX timestamp. If passing the second timestamp parameter remember that it must be converted to a timestamp. This can be done using the PHP strtotime() function. Let me show you an example below of my usual error with the date being pulled from a database and a corrected working version.
echo date("d F Y", $row['my_date']);
// Incorrect: Outputs '01 January 1970'

echo date("d F Y", strtotime($row['my_date']));
// Correct: Outputs the expected date. eg '30 December 2010'

0 comments:

Post a Comment