PHP - 为什么这个日期函数没有错误

发布于 2024-08-29 18:22:53 字数 327 浏览 9 评论 0原文

function convertDT($TS) {
    $TS = strtotime($TS);
    $TS -= date("Z");
    $newTS = date("Y-m-d\TH:i:s\Z", $TS);
    return $newTS;
}

echo "Good: ".convertDT('2010-04-20 01:23:45')."\n";
echo "Bad: ".convertDT('2010-31-20 01:23:45')."\n";

第二个日期返回:1969-12-31T23:00:00Z

为什么?应该出现这个错误吗?

function convertDT($TS) {
    $TS = strtotime($TS);
    $TS -= date("Z");
    $newTS = date("Y-m-d\TH:i:s\Z", $TS);
    return $newTS;
}

echo "Good: ".convertDT('2010-04-20 01:23:45')."\n";
echo "Bad: ".convertDT('2010-31-20 01:23:45')."\n";

The second date returns: 1969-12-31T23:00:00Z

Why? Should this error?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

忘你却要生生世世 2024-09-05 18:22:53

当您为其提供无效时间戳时,strtotime() 返回false。如果您在整数上下文中使用 false ,则它相当于 0 ,因此当您将其传递到此行时:

$newTS = date("Y-m-d\TH:i:s\Z", $TS);

您实际上是根据 的时间戳创建日期0 。就 UNIX 纪元而言,0 是 1970 年 1 月 1 日,这是您获取最终结果的地方。

你最好的选择是这样的:

$TS = strtotime($TS);
if($TS === false) {
    throw new Exception("Invalid timestamp.");
}
//etc.

strtotime() returns false when you give it an invalid timestamp. false is equivalent to 0 if you use it in an integer context, so when you pass it to this line:

$newTS = date("Y-m-d\TH:i:s\Z", $TS);

You are effectively creating a date from a timestamp of 0. In terms of the UNIX epoch, 0 is January 1st, 1970, which is where you're getting your end result from.

Your best bet would be soemthing like this:

$TS = strtotime($TS);
if($TS === false) {
    throw new Exception("Invalid timestamp.");
}
//etc.
煞人兵器 2024-09-05 18:22:53

在第二次约会时,您尝试创建 31 月和 20 日的日期。即使您颠倒了这些日期,也没有意义。可能是一个错字。

On your second date, you are trying to create a date of month 31 and of day 20. Even if you reversed these, it wouldn't make sense. Probably a typo.

陌生 2024-09-05 18:22:53

阅读此 http://php.net/manual/en/function.strtotime.php< /a>

错误/异常

每次调用日期/时间函数
如果时间到了,将会生成一个 E_NOTICE
区域无效,和/或 E_STRICT
或 E_WARNING 消息(如果使用)
系统设置或 TZ 环境
多变的。参见
date_default_timezone_set()

即使输入字符串无效,该函数也不会生成任何错误。

read this http://php.net/manual/en/function.strtotime.php

Errors/Exceptions

Every call to a date/time function
will generate a E_NOTICE if the time
zone is not valid, and/or a E_STRICT
or E_WARNING message if using the
system settings or the TZ environment
variable. See also
date_default_timezone_set()

This function will not generate any error even if input string is not valid.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文