Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does strtotime give different result in different timezone?

I am not sure why strtotime() in PHP returns different result in different timezone even though same date is given as parameter, does anyone know the answer? I also want to know, can I do similar task (converting a datetime to an int to do calculations easily) with another function which gives same result across different timezone?

EDIT:

An example: If I use strtotime('2011-09-19 00:00:00') shouldn't it just return the difference between 'January 1 1970 00:00:00' and '2011-09-19 00:00:00' in seconds ? Why timezone is an issue here? And can I get something which gives just difference without timezone issue?

like image 862
Muhammad Usman Avatar asked Sep 03 '11 18:09

Muhammad Usman


2 Answers

In short: time zone is considered because the Unix Epoch value is considered in GMT.

In broader sense 2011-09-19 00:00:00 comes to Bangladesh almost after 6 hours it is 2011-09-19 00:00:00 in GMT zone. Because of this gap, another 21600 seconds have passed in the GMT zone when the same date appears in BD.

Since the calculation is done in respect to the GMT, you have to add these 21600 seconds to get the actual difference.

like image 168
masnun Avatar answered Sep 28 '22 06:09

masnun


strtotime gives different results in different timezones because it takes timezones into account...

From strtotime's manual:

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC)

This function will use the TZ environment variable (if available) to calculate the timestamp. Since PHP 5.1.0 there are easier ways to define the timezone that is used across all date/time functions. That process is explained in the date_default_timezone_get() function page.

Have a look at mktime().

Since PHP 5.1, you can use date_default_timezone_set before calling mktime or strtotime.

like image 41
Gregory Pakosz Avatar answered Sep 28 '22 07:09

Gregory Pakosz