error: 使用strtotime的注意点有哪些?

最近在开发一个关于游戏榜单的项目,需要区分日榜、周榜、月榜,其中需要用到strtotime函数来计算时间,就会想到strtotime的一些注意点,顺便记录下。

例如:

echo date( "Y-m-d", strtotime( "-1 month", strtotime('2021-03-30')));

//输出 2021-03-02

我们知道 2 月根本没有 30 号,  所以上面的 -1 month 还是跳到了3月2号。所以使用处理strtotime时间一般都需要注意这些问题,不然可能会造成坑。

php5.3之后strtotime函数增加了一些短语,来解决这些问题。

例如:

//获取下个月的最后一天
echo date( "Y-m-d", strtotime( "last day of next month"));
//获取下个月的第一天
echo date( "Y-m-d", strtotime( "first day of next month"));
//获取上个月的最后一天
echo date( "Y-m-d", strtotime( "last day of last month"));
//获取上个月的第一天
echo date( "Y-m-d", strtotime( "first day of last month"));
//获取本月的最后一天
echo date( "Y-m-d", strtotime( "last day of this month"));
//获取本月的第一天
echo date( "Y-m-d", strtotime( "first day of this month"));

其实这个问题,鸟哥的博客:令人困惑的strtotime 也提过,当然我们也可以用mktime函数来解决这些问题,就是麻烦了一点。

猜你喜欢

转载自blog.csdn.net/panjiapengfly/article/details/114738810