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

查看:35
本文介绍了如何根据时区在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 />'."
";

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

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

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

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

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

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

Get the regular timestamp and add the UTC offset

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

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