【PHP】한 달의 첫날과 말일을 취득하는 방법(DateTime 클래스 & Carbon편)

6856 단어 CarbonPHPdatetime

한 달의 첫날과 말일을 얻고 싶습니다.



월초는 반드시 1 일이지만, 후일이되면 그럴 수 없다.

DateTime 클래스를 사용한 검색 방법


date_default_timezone_set('Asia/Tokyo');

$setYear = 2018;
$setMonth = 2;

$date = new DateTime();
$month['first_day'] = $date->setDate($setYear, $setMonth, 1)->format('Y-m-d'); // 日を1で固定値を入れている
$month['last_day']  = $date->setDate($setYear, $setMonth, 1)->format('Y-m-t'); // 日を1で固定値を入れている

var_dump($month);

/* 実行結果

array(2) {
  ["first_day"]=>
  string(10) "2018-02-01"
  ["last_day"]=>
  string(10) "2018-02-28"
}

*/
Y-m-tt

t 지정한 월의 일수. 28 ~ 31

Carbon을 사용하여 얻는 방법


$setYear = 2018;
$setMonth = 2;

$month['first_day'] = Carbon::create($setYear, $setMonth, 1)->firstOfMonth(); // 日を1で固定値を入れている
$month['last_day']  = Carbon::create($setYear, $setMonth, 1)->lastOfMonth();  // 日を1で固定値を入れている

var_dump($month);

/* 実行結果

array(2) {
  ["first_day"]=>
  string(10) "2018-02-01"
  ["last_day"]=>
  string(10) "2018-02-28"
}

*/


【요주의】 인수는 연월일을 합시다


DateTime 클래스의 사양같습니다만,
달만을 인수에 건네주면, 2월등의 경우 반환값이 이상해지는 타이밍이 있는 것 같습니다.

다음은 2018년 6월 29일 tinker에서 Carbon을 실행한 결과
Psy Shell v0.9.6 (PHP 7.2.5-1+ubuntu18.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> use Carbon\Carbon;
>>> Carbon::create(2018, 1)->lastOfMonth();
=> Carbon\Carbon @1517356800 {#2846
     date: 2018-01-31 00:00:00.0 UTC (+00:00),
   }
>>> Carbon::create(2018, 2)->lastOfMonth();
=> Carbon\Carbon @1522454400 {#2839
     date: 2018-03-31 00:00:00.0 UTC (+00:00),
   }
>>> Carbon::create(2018, 3)->lastOfMonth();
=> Carbon\Carbon @1522454400 {#2844
     date: 2018-03-31 00:00:00.0 UTC (+00:00),
   }
>>> Carbon::create(2018, 6)->lastOfMonth();
=> Carbon\Carbon @1530316800 {#2847
     date: 2018-06-30 00:00:00.0 UTC (+00:00),
   }
>>> Carbon::create(2018, 2)->daysInMonth;
=> 31
>>>

왠지 3월의 정보가 돌아온다

다음은 2018년 7월 2일 tinker에서 Carbon을 실행한 결과
Psy Shell v0.9.6 (PHP 7.2.5-1+ubuntu18.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> use Carbon\Carbon;
>>> Carbon::create(2018, 1)->lastOfMonth();
=> Carbon\Carbon @1517356800 {#2846
     date: 2018-01-31 00:00:00.0 UTC (+00:00),
   }
>>> Carbon::create(2018, 2)->lastOfMonth();
=> Carbon\Carbon @1519776000 {#2839
     date: 2018-02-28 00:00:00.0 UTC (+00:00),
   }
>>> Carbon::create(2018, 3)->lastOfMonth();
=> Carbon\Carbon @1522454400 {#2844
     date: 2018-03-31 00:00:00.0 UTC (+00:00),
   }
>>> Carbon::create(2018, 6)->lastOfMonth();
=> Carbon\Carbon @1530316800 {#2847
     date: 2018-06-30 00:00:00.0 UTC (+00:00),
   }
>>> Carbon::create(2018, 2)->daysInMonth;
=> 28
>>>

이쪽은 정상

아무래도 인수에 없는 정보는 현시점의 정보를 사용하고 있는 것 같다.
2018년 6월 29일에 실행했을 때는 인수로서 2018, 2, 29 가 건네받고 있는 것 같고,
2018-02-28 + 1 = 2018-03-01 

되는 것 같습니다.

그러므로 인수에 건네주는 값은 날까지 제대로 합시다.



  • PHP 사용자 #random 채널에 감사드립니다

  • 참고


  • php - How to find the last day of the month from date? - Stack Overflow
  • DateTime 클래스 요약 메모 - Qiita

  • PHP 사용자 의 #random 채널 여러분
  • 좋은 웹페이지 즐겨찾기