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

发布于 2024-12-23 11:14:43 字数 359 浏览 0 评论 0原文

首先代码

    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时间戳也是相同的,

我们如何根据时区打印unix时间戳?

Code first

    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/>';

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

How can we print unix timestamp according to timezone?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

如何视而不见 2024-12-30 11:14:43

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

<?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 偏移量

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";
?>

Get the regular timestamp and add the UTC offset

无声静候 2024-12-30 11:14:43

https://en.wikipedia.org/wiki/Unix_time

Unix 时间,或 POSIX 时间,是一种描述瞬间的系统in time,定义为自 1970 年 1 月 1 日星期四午夜协调世界时 (UTC) 以来经过的秒数

unix 时间戳不受时区设置的影响。设置时区仅影响时间戳值的解释。

https://en.wikipedia.org/wiki/Unix_time

Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of Thursday, January 1, 1970

The unix timestamp isn't affected by a timezone setting. Setting the timezone only affects the interpretation of the timestamp value.

抽个烟儿 2024-12-30 11:14:43

我自己也遇到了同样的问题,这是我可以很快完成的最简单的方法。

$dateTimeZone = new DateTimeZone("America/New_York");
$dateTime = new DateTime("now", $dateTimeZone);
$timeOffset = $dateTimeZone->getOffset($dateTime);

// New time since epoch according to timezone
$newTime = time() + $timeOffset;

echo date("H:i:s", $newTime);

Had the same issue myself, and this is the easiest approach I could do fairly quickly.

$dateTimeZone = new DateTimeZone("America/New_York");
$dateTime = new DateTime("now", $dateTimeZone);
$timeOffset = $dateTimeZone->getOffset($dateTime);

// New time since epoch according to timezone
$newTime = time() + $timeOffset;

echo date("H:i:s", $newTime);
维持三分热 2024-12-30 11:14:43

看到了偏移解决方案的答案,我认为除非你在数据库中以 UTC 或 Unix 时间戳保存时间,否则它们不会有帮助。问题是,当涉及到 getTimestamp() 时,即使您启动该对象,也不会考虑时区...我该如何解释:)...假设您的数据库中有一些带有日期和时间的事件。您还正确配置了时区。在本例中,我将把它们放在 vars 中,这样就更明显了:

$dateTime = '25.08.2018 16:45:15';//some event in your db //can be any valid format
$localTimezone = 'Europe/Berlin';
$dateTimeLocal = new \DateTime($dateTime, new \DateTimeZone($localTimezone));
var_dump($dateTimeLocal->getTimestamp());`

现在...当您执行此操作时,您将日期时间和时区传递给构造函数。您所期望的是,php 会尊重您的时区,并且您会获得与柏林的 16:45 相对应的 UTC 时间戳,冬季为 UTC 15:45,夏季为 UTC 14:45。它不会发生 - 你得到的是对应于 UTC 16:45 的时间戳。如果您现在添加偏移量,您将节省一两个小时。

正确的方法是启动对象,设置/切换时区,创建一个尊重时区的格式化日期时间,然后从格式化日期时间获取时间戳。它可能会慢一点,但它的时区失败证明:

$date = '25.08.2018 16:45:15';//some event in your db //can be any valid format
$format = 'Y-m-d H:i:s';//just a format we will use for this example //also can be any valid format
$localTimezone = 'Europe/Berlin';
$remoteTimezone = 'America/Lima';
$dateTime = new \DateTime($date, new \DateTimeZone($localTimezone));
$dateTime->setTimezone(new \DateTimeZone($remoteTimezone));
$timestampLima = DateTime::createFromFormat($format, $dateTime->format($format))->getTimestamp();

Saw the answers with the offset solution and I think that unless you save you times in the database in UTC or Unix timestamp they won't help. The problem, when it comes to getTimestamp(), is that the timezone is not considered even when you initiate the object... How do I explain it :)... let's say you have some event with date and time in you db. You also have you timezone correctly configured. I'll put these in vars for this example, so it's more visible:

$dateTime = '25.08.2018 16:45:15';//some event in your db //can be any valid format
$localTimezone = 'Europe/Berlin';
$dateTimeLocal = new \DateTime($dateTime, new \DateTimeZone($localTimezone));
var_dump($dateTimeLocal->getTimestamp());`

Now...when you do this, you pass the datetime and your timezone to the constructor. What you would expect is that php respects your timezone and you get UTC timestamp that corresponds to 16:45 in Berlin which would be UTC 15:45 in winter and UTC 14:45 in summer. It won't happen - what you get is timestamp corresponding to UTC 16:45. If you add the offset now you will be hour or two off.

The correct way to do this is to initiate the object, set/switch timezones, create a formatted datetime which respects the timezone and then get timestamp from the formatted datetime. It might be a bit slower, but it's timezone fail prove:

$date = '25.08.2018 16:45:15';//some event in your db //can be any valid format
$format = 'Y-m-d H:i:s';//just a format we will use for this example //also can be any valid format
$localTimezone = 'Europe/Berlin';
$remoteTimezone = 'America/Lima';
$dateTime = new \DateTime($date, new \DateTimeZone($localTimezone));
$dateTime->setTimezone(new \DateTimeZone($remoteTimezone));
$timestampLima = DateTime::createFromFormat($format, $dateTime->format($format))->getTimestamp();
他是夢罘是命 2024-12-30 11:14:43

使用 time() 获得的 unix 时间戳无论如何都不会受到时区的影响。当您想要获取给定日期(例如2022-09-11 13:00)的unix时间戳,或者当您想要以日历方式显示unix时间戳时,时区是相关的。

因此,如果您想获取特定时区中给定日期的 unix 时间戳,请使用 strtotime() 函数并包含时区参数。

$unixTimestampOfDate = strtotime('2022-09-11 13:00 Europe/Berlin');

如果您想在考虑给定时区的情况下以日历方式显示 unix 时间戳,请设置时区默认值,然后使用 date() 函数。

date_default_timezone_set('Europe/Berlin');
echo date('Y-m-d H:i', $unixTimestamp);

The unix timestamp that you get with time() is not influenced in anyway by the timezone. The timezone is relevant when you want to get the unix timestamp of a given date like 2022-09-11 13:00, or when you want to display the unix timestamp in a calendar fashion.

So if you want to get the unix timestamp of a given date in a certain timezone, use the strtotime() function and include the timezone parameter.

$unixTimestampOfDate = strtotime('2022-09-11 13:00 Europe/Berlin');

If you want to display a unix timestamp in a calendar fashion considering a given timezone, set the timezone default and then use the date() function.

date_default_timezone_set('Europe/Berlin');
echo date('Y-m-d H:i', $unixTimestamp);
再可℃爱ぅ一点好了 2024-12-30 11:14:43

这是一个将 unix/gmt/utc 时间戳转换为所需时区的函数。

function unix_to_local($timestamp, $timezone){
    // Create datetime object with desired timezone
    $local_timezone = new DateTimeZone($timezone);
    $date_time = new DateTime('now', $local_timezone);
    $offset = $date_time->format('P'); // + 05:00

    // Convert offset to number of hours
    $offset = explode(':', $offset);
    if($offset[1] == 00){ $offset2 = ''; }
    if($offset[1] == 30){ $offset2 = .5; }
    if($offset[1] == 45){ $offset2 = .75; }
    $hours = ($offset[0] . $offset2) + 0;

    // Convert hours to seconds
    $seconds = $hours * 3600;

    // Add/Subtract number of seconds from given unix/gmt/utc timestamp
    $result = floor( $timestamp + $seconds );

    return $result;
}

Here is a function to convert unix/gmt/utc timestamp to required timezone.

function unix_to_local($timestamp, $timezone){
    // Create datetime object with desired timezone
    $local_timezone = new DateTimeZone($timezone);
    $date_time = new DateTime('now', $local_timezone);
    $offset = $date_time->format('P'); // + 05:00

    // Convert offset to number of hours
    $offset = explode(':', $offset);
    if($offset[1] == 00){ $offset2 = ''; }
    if($offset[1] == 30){ $offset2 = .5; }
    if($offset[1] == 45){ $offset2 = .75; }
    $hours = ($offset[0] . $offset2) + 0;

    // Convert hours to seconds
    $seconds = $hours * 3600;

    // Add/Subtract number of seconds from given unix/gmt/utc timestamp
    $result = floor( $timestamp + $seconds );

    return $result;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文