bobo
bobo

Reputation: 8727

Given an UTC offset and a date time, how can we find its UTC date time in PHP?

For example, I have a date time in this format and its UTC offset is +3:

2011-02-23 05:00:00

So its UTC time is actually:

2011-02-23 02:00:00

But what is the simplest way to do this conversion in PHP?

I have thought of using the DateTimeZone class but as you can see, I only have the offset but not the timezone name. And to construct a DateTimeZone object, the timezone name is required.

Maybe there are some better ways without using DateTimeZone class.

Thanks in advance.

Upvotes: 1

Views: 649

Answers (2)

Alex Guzman
Alex Guzman

Reputation: 56

You can use date() and strtotime() for this.

$in = "2011-02-23 05:00:00";
$offset = "-3 hours";
$out = date('Y-m-d H:i:s',strtotime("$in $offset"));

It's also good to note that with this, you aren't restricted on what you're offsetting. The strtotime() function lets you do all kinds of wonderful things, like "-2 weeks +3 days ...", etc.

You are also free to get any date format from date(), or just use strtotime() alone to get the timestamp.

Upvotes: 1

Jacob
Jacob

Reputation: 8334

Could just modify the date based on the offset. If you are interested in changing this to other timezones then create the date with the UTC timezone.

$date = new DateTime('2011-02-23 05:00:00', new DateTimeZone('UTC'));
$date->modify(sprintf('%s%d hours', $offset < 0 ? '+' : '-', $offset));

Note: This will work even if the offset is a string. i.e. "-3" or "+3"

Then for example if you wanted to see that time in Melbourne, Australia.

$date->setTimezone(new DateTimeZone('Australia/Melbourne'));
echo $date->format('c');

Upvotes: 2

Related Questions