2

I know there are many similar questions, but I didn't find what I exactly need...

So I'm using PHP and I want to show the timestamps from database in the visitor's current timezone.

So far I have done the following:

  1. In PHP, I use $TIME everywhere, which is:

    $TIME = time() - date("Z");

    This should be an absolute reference to the time, with no dst, am I right?

  2. I get the user's timezone offset with javascript (only at the time of the first visit), and store it in minutes:

    var d = new Date(); var tz = -d.getTimezoneOffset();

    Of course, the user can set his/her timezone to another one.

  3. When displaying dates from database, I add the stored amount of time to the timestamp: $timestamp += $TIMEZONE_OFFSET * 60;

    And I format it with date()

This seems to be working well, but I wonder what if it comes to dst.

I thought of changing the user's timezone offset somehow automatically, when it comes to dst, but then all the dates would be changed (those too which are not in the dst period). And not every region uses dst, so I'm really confused how to figure this out :\

2 Answers2

0

First of all, time() and date() depends on INI setting date.timezone as well as on DST too. For absolute time you should use gmmktime() and gmdate() instead.

Information about DST of timezone could be resolved, for example, with DateTimeZone::getTransitions().

Or you can use some 3rd-party services instead.

YuS
  • 2,025
  • 1
  • 15
  • 24
0

I would send all timestamps in Unix date() format, which is UTC-based, independent of timezones, DST and the such. On the PHP side:

$php_timestamp = gettimeofday(true);

On the JavaScript side:

var js_timestamp = new Date(php_timestamp*1000);

Then all the get{FullYear,Month,Date,Hours,...}() and to[Locale]{Date,Time,}String() methods will automatically give results based on the user's (client) timezone.

Edgar Bonet
  • 3,416
  • 15
  • 18