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');
date_default_timezone_set('Asia/Shanghai'); date('Y年m月',$t), |

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment
