繁体   English   中英

UTC日期/时间字符串到时区

[英]UTC Date/Time String to Timezone

如何将UTC的日期/时间字符串(例如2011-01-01 15:00:00)转换为php支持的任何给定时区,例如America / New_York或Europe / San_Marino。

PHP的DateTime对象非常灵活。

$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');

PHP的DateTime对象非常灵活。

由于用户要求提供多个时区选项,因此您可以将其设为通用选项。

通用功能

function convertDateFromTimezone($date,$timezone,$timezone_to,$format){
 $date = new DateTime($date,new DateTimeZone($timezone));
 $date->setTimezone( new DateTimeZone($timezone_to) );
 return $date->format($format);
}

用法:

echo  convertDateFromTimezone('2011-04-21 13:14','UTC','America/New_York','Y-m-d H:i:s');

输出:

2011-04-21 09:14:00

function _settimezone($time,$defaultzone,$newzone)
{
$date = new DateTime($time, new DateTimeZone($defaultzone));
$date->setTimezone(new DateTimeZone($newzone));
$result=$date->format('Y-m-d H:i:s');
return $result;
}

$defaultzone="UTC";
$newzone="America/New_York";
$time="2011-01-01 15:00:00";
$newtime=_settimezone($time,$defaultzone,$newzone);

假设UTC未包含在字符串中,则:

date_default_timezone_set('America/New_York');
$datestring = '2011-01-01 15:00:00';  //Pulled in from somewhere
$date = date('Y-m-d H:i:s T',strtotime($datestring . ' UTC'));
echo $date;  //Should get '2011-01-01 10:00:00 EST' or something like that

或者您可以使用DateTime对象。

通用规范化功能,用于格式化从任何时区到其他时区的任何时间戳。 对于存储关系数据库中不同时区的用户的datetimestamp非常有用。 对于数据库比较,将时间戳存储为UTC并与gmdate('Ymd H:i:s')使用gmdate('Ymd H:i:s')

/**
 * Convert Datetime from any given olsonzone to other.
 * @return datetime in user specified format
 */

function datetimeconv($datetime, $from, $to)
{
    try {
        if ($from['localeFormat'] != 'Y-m-d H:i:s') {
            $datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
        }
        $datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
        $datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
        return $datetime->format($to['localeFormat']);
    } catch (\Exception $e) {
        return null;
    }
}

用法:

 $from = ['localeFormat' => "d/m/YH:i A", 'olsonZone' => 'Asia/Calcutta']; $to = ['localeFormat' => "Ymd H:i:s", 'olsonZone' => 'UTC']; datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00" 

怎么样:

$timezone = new DateTimeZone('UTC');
$date = new DateTime('2011-04-21 13:14', $timezone);
echo $date->format;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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