0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【PHP】期間を指定すると、月初と月末を返してくれる関数を作ったよ

Last updated at Posted at 2022-06-22

環境

php 8.0

この記事の内容

開始年月YYYY-mmと終了年月YYYY-mmを渡すと、月初日と月末日を配列で返す関数をPHPで作りました。

//例えばこんな値を渡すと
$from = '2021-04';
$to = '2022-03';

//こんな配列が返ってきます
[
    ['2021-04-01','2021-04-30'],
    ['2021-05-01','2021-05-31'],
    ['2021-06-01','2021-06-30'],
    ['2021-07-01','2021-07-31'],
    ['2021-08-01','2021-08-31'],
    ['2021-09-01','2021-09-30'],
    ['2021-10-01','2021-10-31'],
    ['2021-11-01','2021-11-30'],
    ['2021-12-01','2021-12-31'],
    ['2022-01-01','2022-01-31'],
    ['2022-02-01','2022-02-28']
]

コードはこちら

詳しい説明は省略します。

sample.php
class Period() 
{
		public function getPeriods($from, $to)
		{
				//from月の初日
			  $firstDayOfDateFrom = $from . '-01';
				//fom月の最終日
			  $lastDayOfDateFrom = date('Y-m-d', strtotime(substr($dateFrom, 0, 7) . 'last day of this month')); 
			
			  $array = [[$firstDayOfDateFrom, $lastDayOfDateFrom]];
			
			  if ($from == $to) {
			  //指定期間が1ヶ月のみだった場合
			      return $array;
			  } else {
			      $dateArray = Period::createMonthlyPeriod($array, $firstDayOfDateFrom, $to);
			      return $dateArray;
			  }
		}
		
		private static function createMonthlyPeriod(&$dateArray, $firstDayOfPreviousMonth, $dateTo)
		{
				//指定期間の最後の月でなくなるまで再帰
				if (substr($firstDayOfPreviousMonth, 0, 7) !== $dateTo) { 
		        $firstDayOfNextMonth = date('Y-m-d', strtotime($firstDayOfPreviousMonth . '+1 month'));
		        $lastDayOfNextMonth = date('Y-m-d', strtotime(substr($firstDayOfNextMonth, 0, 7) . 'last day of this month'));
		        $dateArray[] = [$firstDayOfNextMonth, $lastDayOfNextMonth];
		        Period::createMonthlyPeriod($dateArray, $firstDayOfNextMonth, $dateTo);
		    }
		    return $dateArray;
		}
}		

力技でねじ伏せた感は否めませんw

別の方法あったらぜひ教えてください!

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?