strtotime 函数

strtotime 函数

函数说明

strtotime() — 将任何字符串的日期时间描述解析为 Unix 时间戳

int strtotime ( string $time [, int $now = time() ] )

注意 $time 的日期与时间格式(见底部参考)

局限

strtotime() 在某些情况下 +1 month 的返回结果异常.

$test = strtotime('2017-12-31');

echo date('Y-m-d', strtotime('+1 month', $test));
# 期待:2018-01-31
# 输出:2018-01-31

echo date('Y-m-d', strtotime('+2 month', $test));
# 期待:2018-02-28
# 输出:2018-03-03

正确的用法

$test = strtotime('2017-12-31');

echo date('Y-m-d', strtotime('last day of +1 month', $test));
# 输出:2018-01-31
echo date('Y-m-d', strtotime('last day of +2 month', $test));
# 输出:2018-02-28

在使用 strtotime() 函数的时候,指定每个月的最后一日,防止 +1 month 「溢出」异常结果.

last day of 是在某些月份会「溢出」的时候加,目的是为了取到该月份的最后一日

不相关例子

场景

一个定时任务,每个月的某天某时某分触发(则当前时间可知),求这个月的最后一天日期.

$ crontab -l
0 0 20 * * /usr/bin/php -f index.php # 每个月20号 0:00 执行

方法一

$nextMonth    = strtotime('+1 month'); // now => 2018-09-19 21:57:59
$nextFirstDay = date('Y-m', $nextMonth) . '-01';
$lastDay          = date('Y-m-d', strtotime('-1 day', strtotime($nextFirstDay)));

echo $lastDay;
# 输出:2018-09-30

方法二

echo date('Y-m-t', time()); // time() => 2018-09-19 21:57:59
# 输出:2018-09-30

方法三

echo date('Y-m-d', strtotime('last day of this month')); // now => 2018-09-19 21:57:59
# 输出:2018-09-30

echo date('Y-m-d', strtotime('last day of +0 month')); // now => 2018-09-19 21:57:59
# 输出:2018-09-30

参考:
PHP Manual
日期与时间格式

如果觉得不错,可以给我一个 STAR.

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 2

这个怎么办

$test = strtotime('2017-12-27');

echo date('Y-m-d', strtotime('last day of +1 month', $test));//2018-01-31 实际想要2018-01-27 
5年前 评论

@lovecn 直接使用 echo date('Y-m-d', strtotime('+1 month', $test)); 就好,每个月都会有 27日。加 last day of是在某些月份可能会「溢出」的时候加的,为的就是取到这个月的最后一日。例如,2017-12-29 +2 month 就要加 last day of +2 month,因为2月可能有28日,可能有29日;而 2017-12-28 +2 month 则不需要,因为每个月肯定都有28日。

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!