本文介绍了使用相对日期时的strtotime()的奇怪行为('本周')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've encountered somehow weird behavior of the strtotime() function when dealing with relative date formats.

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

I live in a country, where the first day of the week isn't Sunday but Monday instead. This fact should reflected on strtotime()'s output.

问题是,无论什么语言环境set(我尝试 en_US locale), strtotime()只是怪异,星期一和星期天都不在本周的范围。见下面的例子。

The problem is, that no matter what locale I set (i tried en_US locale too), strtotime() just weirds out and neither Monday nor Sunday appears to be in this week's range. See example below.

今天,2014-02-02(或02/02/2014,如果你会..什么好日子)是星期天。基于此,我试图得到本周的星期一和星期日的日期。两个都是关闭的。

Today, 2014-02-02 (or 02/02/2014, if you will .. what a nice date) is Sunday. Based on that, i tried to get this week's Monday and Sunday dates. Both were off.

<?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-01-27返回,但不是。

If strtotime() thought that a week starts with Sunday, it should have returned 2014-02-02 as 'this week sunday', but it didn't. That means, according to strtotime(), a week starts with Monday. In that case, 'this week monday' should be returning 2014-01-27, but it isn't.

这种行为是不合逻辑的。这是PHP bug吗?我做错了吗?如果这是一个bug,那么解决这个问题的最好办法是什么?

This behavior is illogical. Is this a PHP bug? Am I doing something wrong? In case this is a bug, what would be the best way to workaround this issue?

推荐答案

成为一个bug一个工作可能涉及检查,看看今天是星期天。所以这样的东西:

Weird, this does in fact seem to be a bug. A work around could involve checking to see if "today is a Sunday". So something like:

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

这篇关于使用相对日期时的strtotime()的奇怪行为('本周')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 09:31