【问题标题】:Trying to understand Timestamps and Timezones in PHP试图理解 PHP 中的时间戳和时区
【发布时间】:2010-12-24 08:59:54
【问题描述】:

我有一个需要支持时区的 PHP 应用程序。现在我将数据库中的日期和时间值存储为整数。所以这就是我要做的。

// now create the DateTime object for this time and user time zone
$dtime = new DateTime($date_time, new DateTimeZone($time_zone));
$timestamp = $dtime->format('U');

我不明白的是,即使此人在新西兰(太平洋/奥克兰)并且应用程序使用上述代码存储此日期:24-12-2010 00:00:00,该值返回为: 1293102000

然后使用完全相同的日期/时间并将时区设置为伦敦(欧洲/伦敦)我得到这个时间戳:1293148800

为什么时间戳不同?我认为时间戳与 Unix 纪元的同一日期的秒数相同?

如果它们不同,这意味着当有人在数据库中搜索 24-12-2010 00:00:00 和 24-12-2010 23:59:59 之间的所有记录时,我需要使用用户时区进行创建的时间戳,我必须使用时区首先创建时间戳。

帮助!

【问题讨论】:

    标签: php timezone timestamp


    【解决方案1】:

    因为新西兰的时区是 +1300 UTC,而伦敦是 0 UTC,13 x 3600seconds = 1293148800-1293102000

    由于您已经存储为整数,因此您应该始终使用零 UTC 在构造 $dtime 时跳过时区

    用于测试

    # date_create is procedural style
    $obj =  date_create('24-12-2010 00:00:00', new DateTimeZone('europe/london'));
    echo $obj->format('U');
    
    $obj =  date_create('24-12-2010 00:00:00');
    echo $obj->format('U');
    

    【讨论】:

    • 引用自 php.net:Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT),因此format("U") 应返回 GMT 时间戳,无论时区如何。
    • 嗨,谢谢。您能否再解释一下“在构造 $dtime 时应始终使用零 UTC”您是说我需要创建没有时区的时间戳吗?
    • 所以我的代码应该是: $dtime = new DateTime('24-12-2010 00:00:00'); $timestamp = $dtime->format('U');
    • @Marc - 是的,我认为使用“零 UTC”这个词是不正确的,它应该只是 $dtime = new DateTime($date_time);,你能做一个验证测试吗?
    • $dtime = new DateTime('24-12-2010 00:00:00'); $timestamp = $dtime->format('U'); => 1293102000
    猜你喜欢
    • 2022-01-04
    • 2011-06-02
    • 2014-04-14
    • 2023-03-07
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    相关资源
    最近更新 更多