1

I need to find a way to convert a user specified date and time into a GMT timestamp.

Following the answer by Mahdi here, I'm using the following code to prototype the conversion

$date = new DateTime("09 Jul 2016 18:00:00");
echo gmdate('Y-m-d H:i:s', $date->getTimestamp());

Which returns

2016-07-09 16:00:00

What the response should be is

2016-07-09 17:00:00

Because via using other sources I've worked out that the GMT time is 1 hour behind of the local time where I live (UK).

Any ideas why this peculiar behaviour is happening?

Community
  • 1
  • 1
Umair
  • 11
  • 1
  • 4
  • `$date = new DateTime("09 Jul 2016 18:00:00", new DateTimeZone('UTC')); echo $date->format('U');` – Mark Baker Jul 09 '16 at 17:08
  • If I format that to `Y-m-d H:i:s` it's giving the timestamp of 2016-07-09 18:00:00, which is the same time... – Umair Jul 09 '16 at 17:16
  • You asked for the timestamp, make sure that you have your timezone is set correctly when you render that to a human formatted dte/time value – Mark Baker Jul 09 '16 at 17:49

1 Answers1

0

You never set the timezone to be UTC. Also, it's not necessary to mix DateTime functionality with other PHP date functions as DateTime has all of the tools you need built in.

$date = new DateTime("09 Jul 2016 18:00:00", new DateTimeZone('Europe/London'));
$date->setTimezone(new DateTimeZone('UTC'));
echo $date->format('Y-m-d H:i:s');

Demo

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • This gives `2016-07-09 16:00:00` which is what I was getting initially. – Umair Jul 09 '16 at 17:18
  • My demo says otherwise – John Conde Jul 09 '16 at 17:19
  • Your latest edit (to set the `DateTimeZone` to `Europe/London`) has **fixed it**! However, if the application I'm building is to be used in other places around the world, is there a way to make that part dynamic? – Umair Jul 09 '16 at 17:25
  • Definitely. The timezone value can be placed in a variable and passed to `DateTimeZone()~ just like any other function. – John Conde Jul 09 '16 at 17:56