【问题标题】:How to get if the timestamp is older than a day if I have timestamps with timezones?如果我有带时区的时间戳,如何获取时间戳是否早于一天?
【发布时间】:2020-06-13 15:59:33
【问题描述】:

我有带时区的时间戳,可能格式如下:Weekday, d Month yyyy H:i:s +timezone 例如:Fri, 28 Feb 2020 19:18:26 +010Sat, 29 Feb 2020 21:57:00 +010 如果超过一天,我该如何获取?

【问题讨论】:

    标签: php date timezone


    【解决方案1】:

    您可以使用 preg_match 例如从日期中提取时区

    $tz = preg_match('/([+-]\d+)$/', $datestr, $m) ? $m[0] : '';
    

    然后根据您的日期字符串和当前时间创建DateTime 对象,并针对时区进行调整。如果我们再从当前时间中减去一天并比较两个日期,我们可以确定日期是否超过一天前:

    $datestr = 'Fri, 28 Feb 2020 19:18:26 +010';
    $date = new DateTime($datestr);
    $tz = preg_match('/([+-]\d+)$/', $datestr, $m) ? $m[0] : '';
    $now = new DateTime(date('Y-m-d H:i:s ' . $tz));
    $now->modify('-1 day');
    if ($now > $date) {
        echo "$datestr is more than 1 day ago\n";
    }
    

    输出(截至 3 月 1 日):

    Fri, 28 Feb 2020 19:18:26 +010 is more than 1 day ago
    

    Demo on 3v4l.org

    【讨论】:

      【解决方案2】:

      你的意思是这样的: date('d.m.Y',strtotime("-1 days"));

      【讨论】:

      • 这很酷,但是如果这个日期早于 1 天,我怎么能得到呢?
      • 然后将天数写在括号中,如下所示:echo date('d.m.Y',strtotime("-30 days"));。输出将是 31.01.2020(如果今天的日期是 01.03.2020)
      猜你喜欢
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      • 2019-10-07
      • 2010-12-02
      • 2015-07-26
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      相关资源
      最近更新 更多