如何基于时区在php中获取Unix时间戳 [英] How to get Unix timestamp in php based on timezone

查看:79
本文介绍了如何基于时区在php中获取Unix时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先编码

    echo time() . '<br/>';
echo date('Y-m-d H:i:s') . '<br/>';
date_default_timezone_set('America/New_York'); 

echo time() . '<br/>';
print_r($timezones[$timezone] . '<br/>');
echo date('Y-m-d H:i:s') . '<br/>';

在上面的代码中,日期是根据时区打印的,但是即使设置了默认时区,unix时间戳也是相同的

In the above code the date is printed according to timezone but unix timestamp is same even after setting default timezone

如何根据时区打印UNIX时间戳?

How can we print unix timestamp according to timezone?

推荐答案

Volkerk提供的答案(表示时间戳始终基于UTC)是正确的,但是如果您确实需要解决方法(制作基于时区的时间戳) )看看我的例子.

The answer provided by Volkerk (that says timestamps are meant to be always UTC based) is correct, but if you really need a workaround (to make timezone based timestamps) look at my example.

<?php

//default timezone
$date = new DateTime(null);
echo 'Default timezone: '.$date->getTimestamp().'<br />'."\r\n";

//America/New_York
$date = new DateTime(null, new DateTimeZone('America/New_York'));
echo 'America/New_York: '.$date->getTimestamp().'<br />'."\r\n";

//Europe/Amsterdam
$date = new DateTime(null, new DateTimeZone('Europe/Amsterdam'));
echo 'Europe/Amsterdam: '.$date->getTimestamp().'<br />'."\r\n";

echo 'WORK AROUND<br />'."\r\n";
// WORK AROUND
//default timezone
$date = new DateTime(null);
echo 'Default timezone: '.($date->getTimestamp() + $date->getOffset()).'<br />'."\r\n";

//America/New_York
$date = new DateTime(null, new DateTimeZone('America/New_York'));
echo 'America/New_York: '.($date->getTimestamp() + $date->getOffset()).'<br />'."\r\n";

//Europe/Amsterdam
$date = new DateTime(null, new DateTimeZone('Europe/Amsterdam'));
echo 'Europe/Amsterdam: '.($date->getTimestamp() + $date->getOffset()).'<br />'."\r\n";
?>

获取常规时间戳并添加UTC偏移量

Get the regular timestamp and add the UTC offset

这篇关于如何基于时区在php中获取Unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆