【问题标题】:PHP strtotime() "noon" must go before datePHP strtotime() “中午”必须早于日期
【发布时间】:2015-10-07 19:23:45
【问题描述】:

PHP strtotime() 函数声称能够处理“中午”和“午夜”,但它对我不起作用。

$noon_timestamp = strtotime("August 3 noon");
print date("Y-m-d H:i:s", $noon_timestamp);
1969-12-31 19:00:00

但是,这确实有效:

$twelve_timestamp = strtotime("August 3 12:00 PM");
print date("Y-m-d H:i:s", $twelve_timestamp);
2015-08-03 12:00:00

我发现这确实有效:

$noon_timestamp = strtotime("noon August 3");
print date("Y-m-d H:i:s", $noon_timestamp).PHP_EOL;
2015-08-03 12:00:00

但我不确定为什么需要将“中午”移到日期之前。似乎它应该以任何一种方式工作。我知道用户会尝试这两种方法。

编辑:我想我在Relative Formats 下的 PHP 文档中找到了相关说明:

此规则的例外情况是:“昨天”、“午夜”、“今天”、“中午”和“明天”。请注意,“明天 11:00”和“明天 11:00”是不同的。考虑到今天“2008 年 7 月 23 日”的日期,第一个产生“2008-07-24 11:00”,而第二个产生“2008-07-24 00:00”。原因是这五个语句直接影响当前时间。

最后一句没看懂。 “直接影响当前时间”?这似乎与订单无关。 “明天 11:00”和“明天 11:00”在英语中的意思是一样的。

【问题讨论】:

  • 因为,虽然 PHP 的 strtotime() 函数试图变得聪明,但它并没有内置人类智能水平
  • 如果日期解析拆分了“明天11:00”的细节,则生成明天的日期,然后在该日期调整为11:00;如果它与“明天 11:00”相同,它将在今天生成 11:00,然后调整到 tomorrow 的开头
  • @Rizier123 该文档距离函数文档只有两次点击。我不会阅读整个手册,希望这会记录在某处。我通过谷歌搜索找到了文档。我们正在尝试在这里创建一个问答网站,而不是直接指向手册。
  • @MarkBaker,你应该把它放在一个答案中。不要担心 Rizier,因为他的答案会被警察标记为“不是答案”,因为它只是一个链接答案。

标签: php


【解决方案1】:

我不确定这是一个通用的解决方案,但我做了这个功能:

function arrange_timestring($timestring) {
    $problematic_keywords = array("noon","midnight");
    $keyword_counter = 0;
    foreach($problematic_keywords as $keyword) {
        if (strpos($timestring,$keyword) !== false) {
            $keyword_counter += 1;
            if (strpos($timestring,$keyword) > 0) {
                $timestring = str_replace($keyword, "", $timestring);
                $timestring = $keyword." ".$timestring;
            }
        }
    }
    if ($keyword_counter > 1) {
        return Null; //strings shouldn't have both noon and midnight
    } else {
    return $timestring;
    }
}

然后我的代码按预期工作:

$noon_timestamp = strtotime(arrange_timestring("August 3 noon"));
$twelve_timestamp = strtotime(arrange_timestring("August 3 12:00 PM"));
print date("Y-m-d H:i:s", $noon_timestamp);
2015-08-03 12:00:00
print date("Y-m-d H:i:s", $twelve_timestamp);
2015-08-03 12:00:00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多