【问题标题】:PHP strtotime excludes New Year's Day... How to include the holiday?PHP strtotime 不包括元旦...如何包括假期?
【发布时间】:2020-09-06 08:56:12
【问题描述】:

看起来 PHP 的 strtotime 函数从其结果中排除了元旦。有没有办法强制 strtotime 包含它?其他假期如劳动节似乎没有这个问题(见下面的第三个代码示例)。

谢谢!

// The 1st Wed in Jan 2020 falls on New Year's Day
// But we get: "Wed 2020-01-08" (INCORRECT... it should return "Wed 2020-01-01")
echo date("D Y-m-d", strtotime("First Wednesday " . "2020-01"));

// However, asking for the 1st Thu in Jan 2020 returns the correct result: "Thu 2020-01-02"
echo date("D Y-m-d", strtotime("First Thursday " . "2020-01"));

// Even asking for the 1st Mon in Sep 2020, which is Labor Day returns the correct result: "Mon 2020-09-07"
echo date("D Y-m-d", strtotime("First Monday " . "2020-09"));

【问题讨论】:

    标签: php date datetime strtotime


    【解决方案1】:

    您应该改用"First Wednesday of 2020-01"(注意of)。

    the docs:

    当当前星期几相同时,请注意以下备注 作为日期/时间字符串中使用的星期几:

    [...]

    “ordinal dayname”确实提前到另一天。 (例如“2008 年 7 月 23 日第一个星期三”的意思是“2008-07-30”)。

    [...]

    "ordinal dayname 'of'" 不会提前到另一天。 (例如:“2008 年 7 月的第一个星期二”表示“2008-07-01”)。

    【讨论】:

    • 谢谢!我在文档中完全错过了这一点。 Jan 01 在不使用“of”时得到特殊处理似乎仍然很奇怪,但我会接受的!再次感谢。
    • @bjones1831 那是因为 1 月 1 日是今年(2020 年)的一个星期三。基本上,这就像说“2020 年 1 月 1 日 之后的第一个星期三”,而不是“2020 年 1 月 1 日包括 的第一个星期三”。因此,只有当指定的星期几(左部分)与参考日期(右部分)完全相等时,它才会有所不同。
    • 明白了。而且我刚刚测试了五一假期(5月1日),没有“of”也有同样的错误....谢谢澄清!
    【解决方案2】:

    你可以试试这个。

    echo date("D Y-m-d", strtotime("First Wednesday of January 2020"));
    // Wed 2020-01-01
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      相关资源
      最近更新 更多