태그 보관물: php

날짜에서 해당 월의 마지막 날을 찾는 방법은 무엇입니까?

PHP에서 그 달의 마지막 날을 어떻게 얻을 수 있습니까?

주어진:

$a_date = "2009-11-23"

나는 2009-11-30을 원한다; 그리고 주어진

$a_date = "2009-12-23"

2009-12-31을 원합니다.



답변

t주어진 날짜의 월에 일 수를 반환합니다 (에 대한 문서date 참조 ).

$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));


답변

strtotime ()을 사용하는 코드는 2038 년 이후에 실패합니다. (이 스레드의 첫 번째 답변에 제공된대로) 예를 들어 다음을 사용하십시오.

$a_date = "2040-11-23";
echo date("Y-m-t", strtotime($a_date));

1970-01-31과 같이 대답합니다.

따라서 strtotime 대신 DateTime 함수를 사용해야합니다. 다음 코드는 2038 년 문제없이 작동합니다.

$d = new DateTime( '2040-11-23' );
echo $d->format( 'Y-m-t' );


답변

나는 이것이 조금 늦다는 것을 알고 있지만 DateTime 클래스 PHP 5.3+를 사용하여 이를 수행하는보다 우아한 방법이 있다고 생각합니다 .

$date = new DateTime('now');
$date->modify('last day of this month');
echo $date->format('Y-m-d');


답변

내장 된 PHP 함수 cal_days_in_month ()도 있습니다 .

“이 함수는 지정된 달력에 대해 해당 월의 일 수를 반환합니다.”
http://php.net/manual/en/function.cal-days-in-month .

echo cal_days_in_month(CAL_GREGORIAN, 11, 2009);
// = 30


답변

이것은 작동해야합니다 :

$week_start = strtotime('last Sunday', time());
$week_end = strtotime('next Sunday', time());

$month_start = strtotime('first day of this month', time());
$month_end = strtotime('last day of this month', time());

$year_start = strtotime('first day of January', time());
$year_end = strtotime('last day of December', time());

echo date('D, M jS Y', $week_start).'<br/>';
echo date('D, M jS Y', $week_end).'<br/>';

echo date('D, M jS Y', $month_start).'<br/>';
echo date('D, M jS Y', $month_end).'<br/>';

echo date('D, M jS Y', $year_start).'<br/>';
echo date('D, M jS Y', $year_end).'<br/>';


답변

무엇이 잘못 되었나요-가장 우아한 것은 DateTime

나는 DateTime::createFromFormat하나의 라이너 가 보이지 않는 것이 궁금합니다.

$lastDay = \DateTime::createFromFormat("Y-m-d", "2009-11-23")->format("Y-m-t");


답변

다음 달 1 일의 날짜를 만든 다음 strtotime("-1 day", $firstOfNextMonth)