>  기사  >  php教程  >  strtotime() PHP中的其他用途 上月下月时间不准确

strtotime() PHP中的其他用途 上月下月时间不准确

WBOY
WBOY원래의
2016-06-06 20:11:211723검색

当我们使用PHP获得上个月的时候,一般会使用strtotime('-1 MONTH'),但是这样有时候会不准确,比如 今天是2013-03-31,strtotime('-1 MONTH')的结果是2013-03-03,而不是预期的2013年2月的日期,初步设想是因为这个方法是先查找上个月的天数,然后在使用今天

当我们使用PHP获得上个月的时候,一般会使用strtotime('-1 MONTH'),但是这样有时候会不准确,比如 今天是2013-03-31,strtotime('-1 MONTH')的结果是2013-03-03,而不是预期的2013年2月的日期,初步设想是因为这个方法是先查找上个月的天数,然后在使用今天的时间减去上个月天数。。。

以下有几种方法,可以帮助我们达到预期效果,比如我要返回上个月的月份:
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)),
));
?>

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:PHP的$this变量다음 기사:数组组合问题