如何根据时区在php中获取Unix时间戳

2022-01-16 00:00:00 timezone php unix-timestamp

代码优先

    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

相关文章