0

I am using simplexml_load_file to parse contains of a trip log file (.GPX). In it, the tag <time> records are of the GMT, and I am looking for a PHP funciton or a simple combination of PHP functions to convert it to my local time (GMT+8). I have looked through here and still can not figure out what to do.

To be specific, is there any PHP function which takes in a string like "2013-11-22T04:14:30Z" and returns "2013-11-22 12:14:30" (I wish to display datetime in this format)? I know it can be achieved by writing a function by myself, but I think there could be a standard PHP function that does this.

Ray Yen
  • 55
  • 9
  • Thanks Pekka, I followed the link you provided and found it works. It is just not as simple as what I have imagined PHP might have provided. Something like `timeconvfunc('2013-11-22T04:14:30Z',origTimeZone,convTimezone)`. – Ray Yen Dec 25 '13 at 07:41
  • I don't think such a function exists, seeing as it would do two jobs at once - one, parse the time string, two, convert time zones. – Pekka Dec 25 '13 at 15:45

1 Answers1

0

Pretty easy using strtotime & date:

$time = '2013-11-22T04:14:30';
$time_z = '2013-11-22T04:14:30Z';

$add_time = ' + 8 hours';

$unixtime = strtotime($time);
$unixtime_z = strtotime($time_z);

echo 'Unixtime: ' . date('Y-m-d h:i:s', $unixtime) . '<br />';
echo 'Unixtime Z: ' . date('Y-m-d h:i:s', $unixtime_z) . '<br />';

echo 'Unixtime (+ 8 hours): ' . date('Y-m-d h:i:s', $unixtime . $add_time) . '<br />';
echo 'Unixtime Z (+ 8 hours): ' . date('Y-m-d h:i:s', $unixtime_z . $add_time) . '<br />';

The output would be:

Unixtime: 2013-11-22 04:14:30

Unixtime Z: 2013-11-21 11:14:30

Unixtime (+ 8 hours): 2013-11-22 04:14:30

Unixtime Z (+ 8 hours): 2013-11-21 11:14:30

The key for this to work is the $add_time which is just me adding + 8 hours to the date string. But there are other methods to handle this based on your larger needs & input data.

Community
  • 1
  • 1
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
  • Meh. A proper timezone conversion as shown in the duplicate link above would be much better - it's more flexible and, more importantly, takes into account DST which this code doesn't. – Pekka Dec 25 '13 at 04:13
  • Thanks Jake! But the output of your code is '2013-11-22 08:14:30' instead of '2013-11-22 12:14:30'. It will output the desired result only if I remove 'T' and 'Z' from the input string, like inputting this: '2013-11-22 04:14:30' instead of '2013-11-22T04:14:30Z'. I do not yet understand how it works. – Ray Yen Dec 25 '13 at 07:36
  • @RayYen Not too sure what you are seeing or if you are mixing things up. I just adjusted the answer so it shows you the different variants based on slight variants of your example. Please review to see what I mean. – Giacomo1968 Dec 25 '13 at 19:37