您好,欢迎访问一九零五行业门户网

PHP中使用strtotime函数注意事项

strtotime函数在是大家常用的一个时间日期转换成单位s的一个函数了,但是这个函数有一个细节大家可能没有注意到,就是 使用的时候需要考虑 有31天和 2月份的情况,所以,如果没有考虑这个特殊的情况,那么在每月的31号或者和2月份有关的时间点时候就可能出现开始的那个灵异情况了,这个情况很多朋友都不记得了,但在很多时间这个非常重要,下面举例子来给各位介绍一下。
今天在微博上看到一个小案例,命令行如下:
 代码如下 复制代码
php -r “echo date(‘y/m’,strtotime(‘-2 months’)) . \”\n\”;”
输出结果如下:
2013/03
如果把命令行修改成如下:
 代码如下 复制代码
php -r “echo date(‘y/m’,strtotime(‘-3 months’)) . \”\n\”;”
输出结果如下:
2013/03
这里就奇怪了,怎么两个月前和三个月前的年月份都是一样的,再看看下面的命令行:
 代码如下 复制代码
php -r “echo date(‘y/m’,strtotime(‘-3 months’,strtotime(’2013/05/28′))) . \”\n\”;”
输出结果如下:
2013/02
如果修改命令行为如下:
 代码如下 复制代码
php -r “echo date(‘y/m’,strtotime(‘-3 months’,strtotime(’2013/05/29′))) . \”\n\”;”
输出结果如下:
2013/03
下面这个与预期的结果是一样的,现在说说为什么会出现开始的那个奇怪的坑。
strtotime里的months和 month是30天,使用的时候需要考虑 有31天和 2月份的情况,所以,如果没有考虑这个特殊的情况,那么在每月的31号或者和2月份有关的时间点时候就可能出现开始的那个灵异情况,这个算是strtotime的一个坑吧,为了慎重起见,能不用的时候就尽量别去用这个坑人的东东。
ps:以上所有例子都是在debian6的64位系统下执行,使用命令行方式执行,执行时间是2013-05-30.
上月下月时间不准确
以下有几种方法,可以帮助我们达到预期效果,比如我要返回上个月的月份:
 代码如下 复制代码
echo date('m y', strtotime('midnight first day of -1 month'));
或者:
echo date('m y', strtotime(date('y-m-01')) - 86400);
下方是其他的用途:
 代码如下 复制代码
strtotime('first day of last month');
strtotime('last day of last month');
strtotime('first of last week');
strtotime('first of this week');
strtotime('this week midnight'); // returns monday midnight of this week
strtotime('last week midnight'); // returns monday midnight of last week
strtotime('last week sunday midnight'); // returns sunday midnight of this week
strtotime('-2 weeks sunday midnight'); // returns sunday midnight of last week
其它类似信息

推荐信息