在PHP里获取时间很简单,使用date
函数就可以了,但date
函数获取的是当前时区(php.ini文件里配置的时区)的时间,如果想获取其他时区的时间可以怎么做呢?
获取其它时区的代码
<?php
/**
* 获取不同时区的时间字符串
* @param string $format 字符串格式
* @param string $timeZone 时区
* @return string
*/
function ex_date($format, $timeZone = null) {
if ($timeZone === null) {
$timeZone = date_default_timezone_get();
}
$dateTimeZone = new DateTimeZone($timeZone);
$dateTime = new DateTime();
$dateTime->setTimezone($dateTimeZone);
return $dateTime->format($format);
}
$format = 'Y-m-d H:i:s';
$gmtTime = ex_date($format, 'GMT');
$chinaTime = ex_date($format, 'Asia/Shanghai');
$koreaTime = ex_date($format, 'Asia/Seoul');
$newYorkTime = ex_date($format, 'America/New_York');
$londonTime = ex_date($format, 'Europe/London');
$output =<<<EOT
当前世界各地时间
格林威治(GMT):$gmtTime
中国:$chinaTime
韩国:$koreaTime
纽约:$newYorkTime
伦敦:$londonTime
EOT;
echo nl2br($output);
exit();
以上代码会输出(示例):
当前世界各地时间
格林威治(GMT):2019-02-24 15:09:11
中国:2019-02-24 23:09:11
韩国:2019-02-25 00:09:11
纽约:2019-02-24 10:09:11
伦敦:2019-02-24 15:09:11
需要注意一点的是,同一时刻,虽然不同时区的时间不一样,但通过time
函数获取到的unix时间戳是一样的,也就是说,时间戳跟时区是没有关系的。