2

I receive dates in the following format 2015-01-09T20:46:00+0100 and need to convert it in timestamp. Unfortunately, strtotime function is ignoring the timezone component :

print strtotime('2015-01-09T20:46:00+0100') . "\n";
print strtotime('2015-01-09T20:46:00');

//result is the same with or without timezone:
//1420832760
//1420832760

What is the right way to solve this issue ?

Tom Esterez
  • 21,567
  • 8
  • 39
  • 44

2 Answers2

3

DateTime handles this correctly:

$date = new DateTime('2015-01-09T20:46:00+0100');
echo $date->getTimestamp();
echo "\n";
$date = new DateTime('2015-01-09T20:46:00');
echo $date->getTimestamp();

1420832760
1420836360

Demo

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • lol, why didn't this worked on my localhost? I first though also that `DateTime` works, but on my XAMPP localhost server it doesn't works, do you have a idea? – Rizier123 Jan 13 '15 at 14:21
  • Honestly, I don't. Best guess is a php version bug. What version of PHP are you running? – John Conde Jan 13 '15 at 14:24
  • My PHP version is: `5.5.6`, i tried it on `ideone.com` and `eval.in` and it worked, now i tired it on: `3v4l.org` and it didn't worked look here: http://3v4l.org/cYnDG , it seems to be really strange – Rizier123 Jan 13 '15 at 14:26
  • I think this shouldn't work! Because take a look into the manual->parameters->notes and read the note! http://php.net/manual/en/datetime.construct.php – Rizier123 Jan 13 '15 at 14:33
  • Same for me. DateTime method and strtotime both worked on eval.in but not on my local WAMP (php 5.5.8) – Tom Esterez Jan 13 '15 at 14:33
  • @Rizier123 my interpretation of the note is that the timezone in the input string is used instead of the $timezone param – Tom Esterez Jan 13 '15 at 14:37
0

I fugured out !

uses the default time zone unless a time zone is specified in that parameter http://php.net/manual/en/function.strtotime.php

That's why the result is the same setting or not the timezone :

date_default_timezone_set('Europe/Paris');
print strtotime('2015-01-09T20:46:00+0200');
print "\n";
print strtotime('2015-01-09T20:46:00+0100');
print "\n";
print strtotime('2015-01-09T20:46:00');

print "\n\n";

date_default_timezone_set('UTC');
print strtotime('2015-01-09T20:46:00+0100');
print "\n";
print strtotime('2015-01-09T20:46:00');

output:

1420829160
1420832760
1420832760

1420832760
1420836360

Demo: https://eval.in/241781

Thanks for the help!

Tom Esterez
  • 21,567
  • 8
  • 39
  • 44