0

開始時刻と終了時刻から指定された期間に含まれる各月の日数を計算するにはどうすればよいですか? たとえば、2013 年 4 月 4 日から 2013 年 10 月 6 日までの期間では、各月の何日が含まれますか?

4

1 に答える 1

1

これらの他の回答は、2 つの日付の間の合計日数または月数よりもさらに細分化するための最良の方法には回答していないようです。私はそれを試してみて、これを思いつき、2 つの日付の間の各月の日数を見つけました。

手順は次のようになると思いました。

  1. 開始月の残り日数を計算します (この例では 4 月は 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 に答える