[英]Weird PHP date behavior when trying to get last day of last month
我刚刚注意到 PHP 日期函数的行为很奇怪,有人可以解释我做错了什么吗?
以下代码显示相同的结果
<?php
echo date('Y-m-t');
// Outputs last day of this month: 2016-03-31
echo date('Y-m-t', strtotime("-1 month"));
// For some reason outputs the same: 2016-03-31
echo date('Y-m-t', strtotime("+1 month"));
// Outputs 2016-05-31
可能只是我愚蠢,但有人可以解释我为什么会发生这种情况吗?
在date('Ym-t')
调用中使用t
,您指的是:
t
- 给定月份的天数
如果您尝试过Ymd
您会发现这是 2 个不同的日期:
<?php
var_dump( date('Y-m-d') );
var_dump( date('Y-m-d', strtotime('-1 month') ) );
字符串(10) "
2016-03-31
"
字符串(10) "2016-03-02
"
要解决此问题,您可以使用last day of last month
的strtotime
格式:
<?php
var_dump( date('Y-m-d') );
var_dump( date('Y-m-d', strtotime('last day of last month') ) );
这导致:
字符串(10) "
2016-03-31
"
字符串(10) "2016-02-29
"
尝试date('Ym-d', strtotime("-1 month"))
,显示什么? 3 月 2 日。 为什么? 因为 2 月 31 日不存在,而且 PHP 会进行日期翻转数学运算。
基本问题是“减一个月”的定义非常模糊和不明确。 什么应该发生在像“2月31日”的日期时的土地? 没有好的或正确的答案。 不要让 PHP 来决定结果。 如果您期望得到明确的结果,则从一个月的第一天明确扣除一个月。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.