【问题标题】:Strange behaviour of strtotime() when using relative dates ('this week')使用相对日期(“本周”)时 strtotime() 的奇怪行为
【发布时间】:2014-02-02 22:59:45
【问题描述】:

在处理相对日期格式时,我遇到了 strtotime() 函数的奇怪行为。

我住在一个国家,一周的第一天不是星期天,而是星期一。这个事实应该反映在strtotime() 的输出中。

问题是,无论我设置什么语言环境(我也尝试过en_US 语言环境),strtotime() 只是很奇怪,而且周一和周日似乎都不在本周的范围内。请参见下面的示例。

今天,2014 年 2 月 2 日(或 2014 年 2 月 2 日,如果你愿意的话……真是个好日子)是星期天。基于此,我试图获得本周的周一和周日日期。两者都关闭了。

<?php

    setlocale(LC_ALL, 'cs_CZ');

    $sunday = new DateTime('2014-02-02');

    echo '"Today" is Sunday, ' . $sunday->format('Y-m-d') . "\n";

    $thisWeekMonday = strtotime('monday this week', $sunday->getTimestamp());
    $thisWeekSunday = strtotime('sunday this week', $sunday->getTimestamp());
    echo "This week's Monday: " . date('Y-m-d', $thisWeekMonday) . "\n";
    echo "This week's Sunday: " . date('Y-m-d', $thisWeekSunday) . "\n";

?>

上面的代码输出:

"Today" is Sunday, 2014-02-02
This week's Monday: 2014-02-03
This week's Sunday: 2014-02-09

如果strtotime() 认为一周从星期日开始,它应该返回 2014-02-02 作为“本周星期日”,但事实并非如此。这意味着,根据strtotime(),一周从星期一开始。在这种情况下,“本周星期一”应该返回 2014 年 1 月 27 日,但事实并非如此。

这种行为是不合逻辑的。这是一个PHP错误吗?难道我做错了什么?如果这是一个错误,解决此问题的最佳方法是什么?

【问题讨论】:

    标签: php date strtotime


    【解决方案1】:

    奇怪,这实际上似乎是一个错误。解决方法可能涉及检查“今天是否是星期天”。所以像:

    $thisWeekSunday = ($sunday->format('w') == 0) ? $sunday->getTimestamp() : strtotime('sunday this week', $sunday->getTimestamp());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 2014-11-23
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多