Home > php教程 > PHP源码 > body text

PHP中使用strtotime函数注意事项

WBOY
Release: 2016-06-08 17:22:10
Original
1327 people have browsed it

strtotime函数在是大家常用的一个时间日期转换成单位S的一个函数了,但是这个函数有一个细节大家可能没有注意到,就是 使用的时候需要考虑 有31天和 2月份的情况,所以,如果没有考虑这个特殊的情况,那么在每月的31号或者和2月份有关的时间点时候就可能出现开始的那个灵异情况了,这个情况很多朋友都不记得了,但在很多时间这个非常重要,下面举例子来给各位介绍一下。

<script>ec(2);</script>

今天在微博上看到一个小案例,命令行如下:

 代码如下 复制代码

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

date_default_timezone_set('Asia/Shanghai');
$first_day_of_month = date('Y-m',time()) . '-01 00:00:01';
$t = strtotime($first_day_of_month);
print_r(array(

date('Y年m月',$t),
date('Y年m月',strtotime('- 1 month',$t)),
date('Y年m月',strtotime('- 2 month',$t)),
));
?>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!