我正在处理一组统计数据,我需要指定前一个月的开始时间给定任何开始日期,当时我发现某些日期会产生意外结果:
$theday = '2015-12-31';
for ($i = 1; $i < 6; $i++) {
echo "minus $i month = " . date('Y-m', strtotime ("-$i month" , strtotime ( $theday )) ) . '-01' . "\n";
}
输出:
minus 1 month = 2015-12-01
minus 2 month = 2015-10-01
minus 3 month = 2015-10-01
minus 4 month = 2015-08-01
minus 5 month = 2015-07-01
我做错了什么?获取X日期前一个月的年份和月份的正确方法是什么?
答案 0 :(得分:1)
根据https://derickrethans.nl/obtaining-the-next-month-in-php.html,你可以写“-x月的第一天”。以下代码:
$theday = '2015-12-02';
for ($i = 1; $i < 6; $i++) {
echo "minus $i month = " . date('Y-m-d', strtotime ("first day of -$i month" , strtotime ( $theday )) ) . "\n";
}
结果:
minus 1 month = 2015-11-01
minus 2 month = 2015-10-01
minus 3 month = 2015-09-01
minus 4 month = 2015-08-01
minus 5 month = 2015-07-01