关于strtotime函数不为人知的使用方法

相信很多开发者都用过strtotime这个时间转换函数。那么,你有没有试过如何用这个函数获取到某个月的最后一天或者第一天。

假设现在是2019年3月31日,如果你想拿到上个月的最后一天,也就是2019年2月28日的时间。你会怎么做?

date("Y-m-d", strtotime("-1 month", strtotime("2019-03-31")));

用这一句吗?结果很有意思。猜猜是什么?

2019-03-03

我的PHP版本是7.1.7,这涉及到php的内部处理机制。

虽然这篇博客是转载的,但是风雪之隅的原文解释没有彻底说服我。如果您有什么见解欢迎来和我分享。

从PHP5.3开始呢,date新增了一系列修正短语,来明确这个问题, 那就是”first day of” 和 “last day of”。

正确获取月头月尾时间时间的方式如下:

var_dump(date("Y-m-d", strtotime("last day of -1 month", strtotime("2019-03-31"))));//输出2019-02-28
var_dump(date("Y-m-d", strtotime("first day of +1 month", strtotime("2019-03-31"))));//输出2019-04-01
var_dump(date("Y-m-d", strtotime("first day of next month", strtotime("2019-03-31"))));//输出2019-04-01
var_dump(date("Y-m-d", strtotime("last day of last month", strtotime("2019-03-31"))));//输出2019-02-28

有没有很神奇。

转载自http://www.laruence.com/2018/07/31/3207.html

你可能感兴趣的:(php)