[PHP] strtotime() 함수 익월/전월(+1 month/-1 month) 파라미터 버그

[PHP] strtotime() 함수 익월/전월(+1 month/-1 month) 파라미터 버그

PHP에서 당월의 말일 기준으로 다음달 마지막 일자를 구하려는 경우 아래 구문을 사용하는데 버그가 존재합니다.

<?php
$nowDate = '2019-08-31';

$resultDate = date('Y-m-t', strtotime('+1 month', strtotime($nowDate)));

echo $resultDate;

// 예상 : 2019-09-30
// 결과 : 2019-10-31

strtotime() 함수에서 +1 month 파라미터를 사용하는 경우 단순히 당월의 일수 만큼 더해서 다음달을 구해오는 것으로 확인. 당월이 큰 달(31)이고 다음달이 작은 달(30)인 경우 9월을 넘기고 10월 1일로 계산이 되고 10월의 마지막 일수를 구하니 2019-10-31 이라는 결과값이 출력됩니다.

해결 방법은 +1 month가 아닌 first day of +1 month 파라미터를 사용하는 것입니다.
(반대의 경우 first day of -1 month 사용)

<?php
$nowDate = '2019-08-31';

$resultDate = date('Y-m-t', strtotime('first day of +1 month', strtotime($nowDate)));

echo $resultDate;

// 예상 : 2019-09-30
// 결과 : 2019-09-30

strtotime() 함수의 first day of~ 파라미터는 PHP 5.3x 이상 버전에서 지원됩니다.

%d 블로거가 이것을 좋아합니다: