一般获取上个月的时间我们会用 strtotme("-1 month"),得到上个月的时间戳,但是,经常会出错!
eg:
date('Y-m-d', strtotime('+1 month', strtotime('2016-01-31'))); // 2016-03-02
得出结论:
strtotime('+1 month')只是单纯的在当前的时间上加了31天进行计算,大坑
要规避这个问题,要转换下思路,先找对对应的月份,并获取该月份的总天数是否能满足转换的需要:
写个简单的函数:
eg:function geTadayAgoMonth($num,$timestamp) //$num 1,往前1个月 -1往后一个月 $timestamp 需要转换的时间戳
{
$now=$timestamp?:time();
$now_day=date('d',$now);
if ($num==0) return $now;
$arr=getdate($now);
$temp_month=$arr['mon']+$num;
if($num>0){
//先转换年月
if($temp_month>12){
$year=$arr['year'] +1;
$month=$temp_month-12;
}else{
$year=$arr['year'];
$month=$temp_month;
}
}else{
if($temp_month<1){
$year=$arr['year'] -1;
$month=$temp_month+12;
}else{
$year=$arr['year'];
$month=$temp_month;
}
}
$firstday=$year.'-'.$month.'-01';
$temo_day_num=date('t',strtotime($firstday));
if($temo_day_num
//date('t'),获取当月的总天数
$resutl=$year.'-'.$month.'-'.$temo_day_num;
}else{
$resutl=$year.'-'.$month.'-'.$now_day;
}
return strtotime($resutl.' '.$arr['hours'].':'.$arr['minutes'].':'.$arr['seconds']);
}
print_r(date('Y-m-d H:i:s',geTadayAgoMonth(-1,strtotime('2016-01-31 2:25:36'))));//2015-12-31 02:25:36
依次类推,可以写出 N天、N周的函数。
附注:
getdate ([ int $timestamp = time() ] ) 返回 array
eg:print_r(getdate());
Array
(
[seconds] => 59
[minutes] => 41
[hours] => 11
[mday] => 18
[wday] => 5
[mon] => 10
[year] => 2019
[yday] => 290 //一年中的第几天
[weekday] => Friday
[month] => October
[0] => 1571370119 //数据戳
)