简体   繁体   中英

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.

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. ie "-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');

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM