如何计算每个月有多少天包含在从开始时间和结束时间指定的时间段内? 例如,对于时间段 4/4/13 到 10/6/13,包括每个月多少天?
这些其他答案似乎并没有回答进一步分解它的最佳方式,而不是两个日期之间的总天数或月数。我试了一下,想出了这个来找到两个日期之间每个月的天数。
我认为步骤是这样的:
- 计算开始月份的剩余天数(在此示例中四月有 30 天,所以从 4/4 开始意味着 26 天(
- 计算下个月月初之间的月数和最后一个月(在本例中为 5/1-10/1(5 个月((
- 循环并计算出整月之间的天数
- 加上上个月的总天数(6 天(
-
我认为一个附带要求可能不是你需要的,但会拥有是多年来做到这一点的一种方式。
$daysInMonths = 数组((; $start = DateTime::createFromFormat('n/j/y', '4/4/13'(; $end = DateTime::createFromFormat('n/j/y', '10/6/14'(;
// find days til start of next month $daysInMonths[$start->format('Y')][$start->format('n')] = $start->format('t')-$start->format('j'); // calculate months between start of next month and beginning of last month $start->modify('first day of next month'); $end->modify('first day'); // returns DateInterval object $dateDiff = $start->diff($end); // By multiplying the years by 12 we make sure to account for year spans if ($dateDiff->y > 0) { $months = $dateDiff->m+(12*$dateDiff->y); } else { $months = $dateDiff->m; } // find days in those middle months // $start has been advanced to the next month, so we need to log the days in that month $daysInMonths[$start->format('Y')][$start->format('n')] = $start->format('t')-$start->format('j'); $numMonths = $months; for ($i = 0;$i<$numMonths;$i++) { $start->modify('+1 month'); $daysInMonths[$start->format('Y')][$start->format('n')] = $start->format('t'); } // log the days in the last month $daysInMonths[$end->format('Y')][$end->format('n')] = $end->format('j'); print_r($daysInMonths); // Array ( [2013] => Array ( [4] => 26 [5] => 30 [6] => 30 [7] => 31 [8] => 31 [9] => 30 [10] => 7 ) ) // if you instead did 4/4/13 - 10/6/14 you would get: // Array ( [2013] => Array ( [4] => 26 [5] => 30 [6] => 30 [7] => 31 [8] => 31 [9] => 30 [10] => 31 [11] => 30 [12] => 31 ) [2014] => Array ( [1] => 31 [2] => 28 [3] => 31 [4] => 30 [5] => 31 [6] => 30 [7] => 31 [8] => 31 [9] => 30 [10] => 7 ) )