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

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

WBOY
WBOYOriginal
2016-06-06 20:11:211723browse

当我们使用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)),
));
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP的$this变量Next article:数组组合问题