【问题标题】:php date() functions producing unexpected outputphp date() 函数产生意外的输出
【发布时间】:2011-03-11 04:43:06
【问题描述】:

我正在尝试在 PHP 中执行一些基本的日期和时间戳操作,并且得到了意想不到的结果。我正在尝试获取现有时间戳$startDate 的仅包含年、月和日的时间戳(即上午 12:00 的日期的时间戳)。不过,它也在更改日期,如下面的代码所示。

$startDateString = date("Y-M-j", $startDate);
$startDateTimestamp = strtotime($startDateString);
echo "$startDate == $startDateTimestamp ?<br>";
echo date("Y-M-j", $startDate)." == ".date("Y-M-j", $startDateTimestamp)." ?<br>";

这给了我以下输出:

1299299589 == 1298952000 ?
2011-Mar-4 == 2011-Feb-28 ?

虽然我不希望时间戳相同(因为 $startDate 不一定在上午 12:00),但我看不出日历日期是如何不同的。我做错了什么?

【问题讨论】:

标签: php date timestamp


【解决方案1】:

来自strtotime 文档:

日期/时间字符串。有效格式在Date and Time Formats 中进行了解释。

至于你要解决的问题,你可以把其他的东西传给strtotime,比如relative formats

strtotime('midnight', $startDate);

例如,回显当前时间的午夜(如果午夜令人困惑,您也可以使用今天):

echo date('Y-m-d H:i:s', strtotime('midnight'));

“今天”和“午夜”

时间设置为 00:00:00

当然,我是DateTime 对象的忠实粉丝。

$date = new DateTime($startDate);
$date->modify('midnight');
echo $date->format('Y-m-d H:i:s');

【讨论】:

  • 这也很有帮助。如果我能选择两个正确的答案!
【解决方案2】:

经过一些简短的测试,我注意到strtotime() 无法正确解析Y-M-j 格式。要解决此问题,请使用标准格式,例如 RFC822 date time formatISO-8601 date time format 或改用 j-M-Y

【讨论】:

    【解决方案3】:

    我通常使用“Y-m-d”格式来完成类似的任务,并且很有效:

    $startDateString = date("Y-m-d", $startDate);
    $startDateTimestamp = strtotime($startDateString);
    echo "$startDate == $startDateTimestamp ?<br>";
    echo date("Y-m-d", $startDate)." == ".date("Y-m-d", $startDateTimestamp)." ?<br>";
    

    【讨论】:

      猜你喜欢
      • 2019-11-02
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多