Question

I do

strtotime("2008-09-04")

Where 09 is the month and 04 is the day and I get the result:

1220500800

Which is Thu, 04 Sep 2008 04:00:00 GMT. Where does those 4 hours come from? I should get 1220486400 instead of 1220500800 from strtotime.

Was it helpful?

Solution

You can set timezone globally with function date_default_timezone_set('UTC');, or you can just set timezone locally when you call strtotime() function like:

echo strtotime("2008-09-04 +0000"); # 1220486400

OTHER TIPS

As people above have said, you're likely suffering from a time zone mismatch. This function may be of use in debugging the issue: http://us3.php.net/date_default_timezone_get

The most common problems with PHP's strtotime are timezones and date-time formats. I will address those 2 points.

  1. First the format. As suggested by others on stackoverflow use the iso 8601 date format YYYY-MM-DD (https://www.iso.org/iso-8601-date-and-time-format.html). For example, September 27, 2012 is represented as 2012-09-27.
  2. Next the timeszones. The best of all , do not use any timezone use the Universal Coordinated Time UTC (which is universal time and corresponds with GMT without Daylight Saving). UTC is the time standard commonly used across the world. The world's timing centers have agreed to keep their time scales closely synchronized - or coordinated - therefore the name Coordinated Universal Time (https://www.timeanddate.com/time/aboututc.html).

So now we have the picture clear. To convert a date time into unixtimestamp do:

// Saves your local set Timezone.
$saveDDTZ = date_default_timezone_get(); 
// Sets the timezone to UTC
date_default_timezone_set("UTC");
// Converts a date-time into a unix timestamp (= 1560470400).
$unixTS = strtotime( "2019-06-14 00:00:00 UTC");
// Restore the timezone
date_default_timezone_set($saveDDTZ");

To restore a unix timestamp to a Date use:

// Saves your local set Timezone.
$saveDDTZ = date_default_timezone_get(); 
// Sets the timezone to UTC
date_default_timezone_set("UTC");|
$unixTS = 1560470400
$dateTime = date("Y-m-d H:i:s", $unixTS);
// Restore the timezone
date_default_timezone_set($saveDDTZ");

If you want to change the UTC date into a TimeZone use the difference of the UTC and the TimeZone and the Daylight Saving.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top