2

I get log files timestamped using the ISO8601 format from devices in different time zones. Filtering such a file for some values including the timestamp, I could plot certain metrics over time. The issue is the timestamp changes to time zone of the server where the script was run, instead of what is specified in the log file.

Here is an example of what I am doing:

$d = new DateTime();
$d->format('c');
$d->setTimestamp(strtotime("2015-01-19T10:20:24-0500"));
$tz = $d->getTimezone();
echo $tz->getName()."<br/>";
echo $d->format(DateTime::ISO8601)."<br/>";

If I run this script on a server hosted in Australia, the output shows:

Australia/Melbourne
2015-01-20T02:20:24+1100

Instead of GMT-5, the time is shown in GMT+11. Any idea how to retain the time zone from the log file?

Thank you.

Heelara
  • 861
  • 9
  • 17

3 Answers3

1

This issue has been reported in the documentation: http://php.net/manual/en/datetime.format.php#114366

Try:

<?php
$d = new ...
$d->setTimezone( $d->getTimeZone() );
echo $d->format(DateTime::ISO8601)."<br/>";
?>

References:

http://php.net/manual/en/datetime.gettimezone.php

pyb
  • 4,813
  • 2
  • 27
  • 45
  • Bugs should not be **reported** in comments :) – Glavić Jan 28 '15 at 05:51
  • @BobM, thanks for that. It does look like the same issue. I tried your suggestion after changing `date_default_timezone_set( $d->getTimezone()->getName() );`, as it expects a string. However, the output still adopts the server's time zone. – Heelara Jan 28 '15 at 08:37
  • updated with ```$d->setTimezone( $d->getTimeZone() );``` (I don't believe it, but ...) – pyb Jan 28 '15 at 15:43
  • Related: http://stackoverflow.com/questions/2505681/timezone-conversion-in-php and http://stackoverflow.com/questions/5746531/utc-date-time-string-to-timezone – pyb Jan 28 '15 at 15:44
1

Thanks again, @pyb! As the time zone info is not available a prior, I modified based on your suggestion to use DateTime::createFromFormat (). Here is what I did:

$d = date_create_from_format ( "Y-m-d\TH:i:se" , "2015-01-19T10:20:24-0500" );
echo $d->format(DateTime::ISO8601)."<br/>";

Now, I see the output I am after:

2015-01-19T10:20:24-0500
Heelara
  • 861
  • 9
  • 17
0

Found here: http://www.pontikis.net/tip/?id=29

function date_convert($dt, $tz1, $df1, $tz2, $df2) {
  // create DateTime object
  $d = DateTime::createFromFormat($df1, $dt, new DateTimeZone($tz1));
  // convert timezone
  $d->setTimeZone(new DateTimeZone($tz2));
  // convert dateformat
  return $d->format($df2);
}

Examples Convert datetime 28/10/2013 02:00:00 in Europe/Athens to UTC timastamp:

date_convert('28/10/2013 02:00:00', 'Europe/Athens', 'd/m/Y H:i:s', 'UTC', 'YmdHis');
pyb
  • 4,813
  • 2
  • 27
  • 45