ホームページ  >  記事  >  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变量次の記事:数组组合问题