0

如何计算从开始时间和结束时间指定的时间段内每个月有多少天?例如,从 13 年 4 月 4 日到 13 年 10 月 6 日,每个月有多少天?

4

1 回答 1

1

那些其他答案似乎并没有回答最好的方法来进一步分解它,而不是两个日期之间的总天数或月数。我试了一下,想出了这个来找出两个日期之间每个月的天数。

我想这些步骤会是这样的:

  1. 算出开始月份的剩余天数(在此示例中,四月有 30 天,因此从 4 月 4 日开始意味着 26 天)
  2. 计算下月初和上个月之间的月数(在本例中为 5/1-10/1(5 个月))
  3. 循环计算整个月份之间的天数
  4. 加上上个月的总天数(6天)
  5. 我认为的一个附带要求可能不是您需要的,但最好有一个方法可以在多年内做到这一点。

    $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 ) )
    
于 2013-10-06T00:23:51.683 回答