在php中有个叫做strtotime的函数。strtotime 实现功能:获取某个日期的时间戳,或获取某个时间的时间戳。strtotime 将任何英文文本的日期时间描述解析为unix时间戳
今天写程序的时候,突然发现了很早以前写的获取月份天数的函数,经典的switch版,但是获得上月天数的时候,我只是把月份-1了,估计当时太困了吧,再看到有种毛骨悚然的感觉,本来是想再处理一下的,但是一想肯定还有什么超方便的方法,于是找到了下面这个版本,做了一点小修改。
获取本月日期:
function getmonth($date){
$firstday = date("y-m-01",strtotime($date));
$lastday = date("y-m-d",strtotime("$firstday +1 month -1 day"));
return array($firstday,$lastday);
}
$firstday是月份的第一天,假如$date是2014-2这样的话,$firstday就会是2014-02-01,然后根据$firstday加一个月就是2014-03-01,再减一天就是2014-02-28,用date()和strtotime()真是太方便了。
获取上月日期:
function getlastmonthdays($date){
$timestamp=strtotime($date);
$firstday=date('y-m-01',strtotime(date('y',$timestamp).'-'.(date('m',$timestamp)-1).'-01'));
$lastday=date('y-m-d',strtotime("$firstday +1 month -1 day"));
return array($firstday,$lastday);
}
上月日期需要先获取一个时间戳,然后在月份上-1就ok了,超智能的date()会把2014-0-1这种东西转换成2013-12-01,太爽了。
获取下月日期:
function getnextmonthdays($date){
$timestamp=strtotime($date);
$arr=getdate($timestamp);
if($arr['mon'] == 12){
$year=$arr['year'] +1;
$month=$arr['mon'] -11;
$firstday=$year.'-0'.$month.'-01';
$lastday=date('y-m-d',strtotime("$firstday +1 month -1 day"));
}else{
$firstday=date('y-m-01',strtotime(date('y',$timestamp).'-'.(date('m',$timestamp)+1).'-01'));
$lastday=date('y-m-d',strtotime("$firstday +1 month -1 day"));
}
return array($firstday,$lastday);
}
下月日期的代码看起来比较长一点,因为date()转不了类似2014-13-01这种东西,它会直接回到1970,所以前面需要处理一下12月的问题,除了12月就直接月份+1就ok啦。
总得来说,还是很方便的,日期函数太强大了。
最后简单介绍下strtotime的用法
获取指定日期的unix时间戳
strtotime(2009-1-22) 示例如下:
echo strtotime(2009-1-22)
结果:1232553600
说明:返回2009年1月22日0点0分0秒时间戳
获取英文文本日期时间
示例如下:
便于比较,使用date将当时间戳与指定时间戳转换成系统时间
(1)打印明天此时的时间戳strtotime(+1 day)
当前时间:
echo date(y-m-d h:i:s,time())
结果:2009-01-22 09:40:25
指定时间:
echo date(y-m-d h:i:s,strtotime(+1 day))
结果:2009-01-23 09:40:25
(2)打印昨天此时的时间戳strtotime(-1 day)
当前时间:
echo date(y-m-d h:i:s,time())
结果:2009-01-22 09:40:25
指定时间:
echo date(y-m-d h:i:s,strtotime(-1 day))
结果:2009-01-21 09:40:25
(3)打印下个星期此时的时间戳strtotime(+1 week)
当前时间:
echo date(y-m-d h:i:s,time())
结果:2009-01-22 09:40:25
指定时间:
echo date(y-m-d h:i:s,strtotime(+1 week))
结果:2009-01-29 09:40:25
(4)打印上个星期此时的时间戳strtotime(-1 week)
当前时间:
echo date(y-m-d h:i:s,time())
结果:2009-01-22 09:40:25
指定时间:
echo date(y-m-d h:i:s,strtotime(-1 week))
结果:2009-01-15 09:40:25
(5)打印指定下星期几的时间戳strtotime(next thursday)
当前时间:
echo date(y-m-d h:i:s,time())
结果:2009-01-22 09:40:25
指定时间:
echo date(y-m-d h:i:s,strtotime(next thursday))
结果:2009-01-29 00:00:00
(6)打印指定上星期几的时间戳strtotime(last thursday)
当前时间:
echo date(y-m-d h:i:s,time())
结果:2009-01-22 09:40:25
指定时间:
echo date(y-m-d h:i:s,strtotime(last thursday))
结果:2009-01-15 00:00:00
以上示例可知,strtotime能将任何英文文本的日期时间描述解析为unix时间戳,我们结合mktime()或date()格式化日期时间获取指定的时间戳,实现所需要的日期时间。
以上就是php 使用strtotime获取上个月、下个月、本月的日期代码实例的详细内容。