引言与背景
在编写程序时,偶然翻出早期编写的获取月份天数的函数,采用经典的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。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即可。
总体而言,该方法非常实用,PHP的日期函数功能十分强大。
最后简要介绍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()格式化输出,即可灵活获取所需的日期时间。