we are building a site which will be viewed globally therefore need our dates and times to be timezone aware. I am using the library from https://bitbucket.org/pellepim/jstimezonedetect to recover the timezone of the user and also whether they observer DST.
What my question was after retrieving this information I am slightly confused what to do with it. We store all information in UTC in the database however when we receive the offset from the library how do we deal with the DST and whether they are from the Northern or Southern hemisphere. Also how do we deal with it on the server side. My thoughts are to handle all dates and times in standard UTC on PHP and then apply the offset once dealing with the views.
Any help would be greatly appreciated.
Kind Regards
First of all, you should use jsTimezoneDetect only to guess the time zone of the user. It should be user configurable, both because it can be incorrect, and because the users might want to use another time zone than what he really is in. At least if you have a system where users log in or if you have a system where the users is entering times.
For just temporary visitors that are only viewing things, displaying the time in whatever timezone the user happens to be in should be fine, although you can get things an hour wrong if jsTimezoneDetect guesses the wrong timezone and daylight saving rules are different. If you are relying on jsTimezoneDetect's guess, make sure you clearly display what timezone you are guessing the user is in.
Secondly, you need to convert the UTC dates to the time zone that the user has configured (or jsTimezoneDetect has guessed). You do that by using the zoneinfo/tz/Olsen database (one database, many names) which luckily PHP supports.
Most recipes to do this in PHP that I can find involves setting the timezone for php as a whole and then formatting the date. Don't do that, that is insane, keep the php's timezone the same as your systems timezone at all times.
Instead there are in the DateTime library's DateTimeZone objects and support to set the timezone for DateTimes and format them. That's the way to go forward.
So you could do something like this. First create a DateTime object in UTC with the data you get from the database.
php > $date = new DateTime('2000-01-01', new DateTimeZone('UTC'));
php > echo $date->format('Y-m-d H:i:sP') . "\n";
2000-01-01 00:00:00+00:00
Then you can convert it to a user timezone:
php > $date->setTimezone(new DateTimeZone('Pacific/Chatham'));
php > echo $date->format('Y-m-d H:i:sP') . "\n";
2000-01-01 13:45:00+13:45
Or another one:
php > $date->setTimezone(new DateTimeZone('US/Eastern'));
php > echo $date->format('Y-m-d H:i:sP') . "\n";
1999-12-31 19:00:00-05:00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With