当31天月份结束时调用DateTime时,会发生月份重复 [英] Month duplication occurs when DateTime called on end of a 31 day month
问题描述
在5月的最后一天(31日)运行以下命令时,我发生了一些奇怪的行为.如果我将系统时间更改为5月30日或6月的最后一天(30日),则它将正常运行.
I have some strange behaviour happening when I run the following on the last day of May (31st). If I change my system time to 30th May, or the last day of say, June (30th), it functions normally.
但是由于某种原因,它会在31日跳过下个月(六月),而是将其替换为七月.因此它将输出两次七月.这是一个示例:
For some reason though, on the 31st, it will skip the next month (June), and instead replace it with July. So it will output July twice. Here is an example:
31 days in 05, 31 days in 07, 31 days in 07, 31 days in 08,
生成以上代码的代码
<?php
$datepicker_month_range = 3;
// create an array of dates for a number of months specified by the user. 0 is used for this month
for ($month = 0; $month <= $datepicker_month_range; $month++) {
$dt_dates = new DateTime();
$dt_dates->add(new DateInterval("P{$month}M")); // example, P1M == plus 1 month
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $dt_dates->format('m'), $dt_dates->format('Y'));
echo $days_in_month." days in ".$dt_dates->format('m').", ";
for ($day = 1; $day <= $days_in_month; $day++) {
$date = $dt_dates->format('Y')."-".$dt_dates->format('m')."-".sprintf('%02d', $day); // leading zeros 05-..
$month_days[] = $date;
}
}
//print_r($month_days);
?>
稍后,如果运行 print_r($ month_days)
,则将输出完整的日期,与上一个表达式一样,输出的7月将输出两次.
Later on, if print_r($month_days)
is run, the complete dates are outputted with July outputted twice like in the previous expression.
是什么导致这种行为?
谢谢.
推荐答案
Ok, after reading the comments, it seems this is a duplicate of PHP DateTime::modify adding and subtracting months
但是这是我如何解决此问题的方法.
but here is how I got around the problem.
$month_beginning = $dt_dates->format('Y-m-01');
$dt_dates = new DateTime($month_beginning); // rollback the date to the first so we can increment months safely
在一起
for ($month = 0; $month <= $datepicker_month_range; $month++) {
$dt_dates = new DateTime();
$month_beginning = $dt_dates->format('Y-m-01');
$dt_dates = new DateTime($month_beginning); // rollback the date to the first so we can increment months safely
$dt_dates->add(new DateInterval("P{$month}M")); // P1M == plus 1 month
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $dt_dates->format('m'), $dt_dates->format('Y'));
//echo $days_in_month." days in ".$dt_dates->format('m').", ";
for ($day = 1; $day <= $days_in_month; $day++) {
$date = $dt_dates->format('Y')."-".$dt_dates->format('m')."-".sprintf('%02d', $day); // leading zeros 05-..
$month_days[] = $date; // holds dates for datepicker month ranges
}
}
这篇关于当31天月份结束时调用DateTime时,会发生月份重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!