날짜로부터 월의 마지막 날을 어떻게 찾을 수 있습니까?
PHP로 월말일을 가져오려면 어떻게 해야 하나요?
지정:
$a_date = "2009-11-23"
2009-11-30을 원합니다.
$a_date = "2009-12-23"
2009-12-31을 원합니다.
t
는 특정 날짜의 월수를 반환합니다(의 문서를 참조).
$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 대신 Date Time 함수를 사용해야 합니다.다음 코드는 2038년 문제 없이 작동합니다.
$d = new DateTime( '2040-11-23' );
echo $d->format( 'Y-m-t' );
좀 늦은 감이 있긴 하지만 좀 더 우아한 방법이 있을 것 같아요PHP 5.3+
[ Date Time ]클래스를 사용합니다.
$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/>';
저에게 가장 우아한 것은
원라이너가 보이지 않는가?
$lastDay = \DateTime::createFromFormat("Y-m-d", "2009-11-23")->format("Y-m-t");
PHP 5.3+ 를 사용하고 있는 경우는, 이것을 사용해 주세요.
$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');
다음 달 마지막 날짜를 찾으려면 다음과 같이 수정하십시오.
$date->modify('last day of 1 month');
echo $date->format('Y-m-d');
기타 등등..
다음 달 첫 번째 날짜로 만든 다음strtotime("-1 day", $firstOfNextMonth)
몇 가지 방법으로 월말일을 찾을 수 있습니다.단, PHP strtotime() 및 date() 함수를 사용하여 실행할 수 있습니다.최종 코드는 다음과 같습니다.
$a_date = "2009-11-23";
echo date('Y-m-t',strtotime($a_date));
그러나 PHP > = 5.2를 사용하는 경우 새로운 DateTime 개체를 사용하는 것이 좋습니다.예를 들어 다음과 같습니다.
$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');
또, 다음과 같은 독자적인 기능을 사용해 해결할 수 있습니다.
/**
* Last date of a month of a year
*
* @param[in] $date - Integer. Default = Current Month
*
* @return Last date of the month and year in yyyy-mm-dd format
*/
function last_day_of_the_month($date = '')
{
$month = date('m', strtotime($date));
$year = date('Y', strtotime($date));
$result = strtotime("{$year}-{$month}-01");
$result = strtotime('-1 second', strtotime('+1 month', $result));
return date('Y-m-d', $result);
}
$a_date = "2009-11-23";
echo last_day_of_the_month($a_date);
솔루션은 여기 있습니다.
$lastday = date('t',strtotime('today'));
요즘 Date Time은 당신이 월과 연도가 있다면 이것을 매우 편리하게 할 수 있습니다.
$date = new DateTime('last day of '.$year.'-'.$month);
다른 DateTime 오브젝트로부터,
$date = new DateTime('last day of '.$otherdate->format('Y-m'));
PHP DateTime에 Carbon API 확장을 사용하면 다음과 같이 달의 마지막 날을 얻을 수 있습니다.
$date = Carbon::now();
$date->addMonth();
$date->day = 0;
echo $date->toDateString(); // use toDateTimeString() to get date and time
datetime과 함께 사용할 수도 있습니다.
$date = new \DateTime();
$nbrDay = $date->format('t');
$lastDay = $date->format('Y-m-t');
PHP DateTime용 Carbon API 확장
Carbon::parse("2009-11-23")->lastOfMonth()->day;
또는
Carbon::createFromDate(2009, 11, 23)->lastOfMonth()->day;
돌아온다
30
$date1 = $year.'-'.$month;
$d = date_create_from_format('Y-m',$date1);
$last_day = date_format($d, 't');
만약 당신이 한 달이 있다면 그 달의 마지막 날짜를 잡으세요.
public function getLastDateOfMonth($month)
{
$date = date('Y').'-'.$month.'-01'; //make date of month
return date('t', strtotime($date));
}
$this->getLastDateOfMonth(01); //31
2 행의 코드로 종료합니다.
$oDate = new DateTime("2019-11-23");
// now your date object has been updated with last day of month
$oDate->setDate($oDate->format("Y"),$oDate->format("m"),$oDate->format("t"));
// or to just echo you can skip the above line using this
echo $oDate->format("Y-m-t");
Zend_Date를 사용하면 매우 간단합니다.
$date->setDay($date->get(Zend_Date::MONTH_DAYS));
날짜('t')가 아닌 mktime을 사용하는 다른 방법:
$dateStart= date("Y-m-d", mktime(0, 0, 0, 10, 1, 2016)); //2016-10-01
$dateEnd = date("Y-m-d", mktime(0, 0, 0, 11, 0, 2016)); //This will return the last day of october, 2016-10-31 :)
따라서 31, 30 또는 29 중 하나를 계산합니다.
cal_days_in_month에 strtotime을 다음과 같이 사용하고 있습니다.
$date_at_last_of_month=date('Y-m-d', strtotime('2020-4-1
+'.(cal_days_in_month(CAL_GREGORIAN,4,2020)-1).' day'));
완전한 기능은 다음과 같습니다.
public function get_number_of_days_in_month($month, $year) {
// Using first day of the month, it doesn't really matter
$date = $year."-".$month."-1";
return date("t", strtotime($date));
}
다음과 같이 출력됩니다.
echo get_number_of_days_in_month(2,2014);
출력: 28
월말에는 여러 가지 방법이 있습니다.
//to get last day of current month
echo date("t", strtotime('now'));
//to get last day from specific date
$date = "2014-07-24";
echo date("t", strtotime($date));
//to get last day from specific date by calendar
$date = "2014-07-24";
$dateArr=explode('-',$date);
echo cal_days_in_month(CAL_GREGORIAN, $dateArr[1], $dateArr[0]);
늦었지만 다음과 같이 간단한 방법이 몇 가지 있습니다.
$days = date("t");
$days = cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'));
$days = date("j",mktime (date("H"),date("i"),date("s"),(date("n")+1),0,date("Y")));
mktime()을 사용하면 모든 시간을 완벽하게 제어할 수 있습니다.예.
echo "<br> ".date("Y-n-j",mktime (date("H"),date("i"),date("s"),(11+1),0,2009));
날짜를 0으로 설정하고 달을 1 위로 이동하면 전달의 마지막 날이 됩니다. 0과 음수는 다른 논쟁에서 비슷한 영향을 미칩니다.PHP: mktime - 수동
몇몇이 말했듯이 strtotime이 가장 확실한 방법은 아니며 어느 것도 쉽게 다재다능하지는 않다.
몇 달 전으로 돌아가고 싶다면 이런 것도 할 수 있어요.
$list = [
0, 1, 2, 3
];
$date = new \Datetime();
$dates = [];
foreach($list as $item)
{
$set = clone $date;
$set->modify("-$item month ");
$dates[] = $set->modify("last day of this month");
}
return $dates;
저는 https://github.com/normandqq/Date-Time-Helper의 date time helper class에서 그것을 포장했습니다.$dateLastDay = Model_DTHpr::getLastDayOfTheMonth();
그리고 그것은 끝났다.
$startDate = '2011-12-01';
$endDate = date('Y-m');
while (true) {
try {
$startDateTime = new DateTime($startDate);
$startDateTime->add(new DateInterval('P1M'));
$startDate = $startDateTime->format('Y-m-d');
$endTime = $startDateTime->format('Y-m-t');
echo $startDate . ' => ' . $endTime . PHP_EOL;
if ($startDateTime->format('Y-m') == $endDate) {
break;
}
} catch (Exception $exception) {
var_dump($exception->getMessage());
break;
}
}
많은 솔루션을 테스트한 결과, 이것이 가장 효과적입니다.
function first_last_day($string, $first_last, $format) {
$result = strtotime($string);
$year = date('Y',$result);
$month = date('m',$result);
$result = strtotime("{$year}-{$month}-01");
if ($first_last == 'last'){$result = strtotime('-1 second', strtotime('+1 month', $result)); }
if ($format == 'unix'){return $result; }
if ($format == 'standard'){return date('Y-m-d', $result); }
}
다음 달 마지막 날이 필요했는데 누군가 필요할지도 몰라
echo date("Y-m-t", strtotime("next month")); //is 2020-08-13, return 2020-09-30
이것은 월말의 보다 우아한 방법입니다.
$thedate = Date('m/d/Y');
$lastDayOfMOnth = date('d', mktime(0,0,0, date('m', strtotime($thedate))+1, 0, date('Y', strtotime($thedate))));
'어울리지 않다'를 쓰면 요.t
날짜 함수에서 특정 월의 일수를 가져옵니다.
코드는 다음과 같습니다.
function lastDateOfMonth($Month, $Year=-1) {
if ($Year < 0) $Year = 0+date("Y");
$aMonth = mktime(0, 0, 0, $Month, 1, $Year);
$NumOfDay = 0+date("t", $aMonth);
$LastDayOfMonth = mktime(0, 0, 0, $Month, $NumOfDay, $Year);
return $LastDayOfMonth;
}
for($Month = 1; $Month <= 12; $Month++)
echo date("Y-n-j", lastDateOfMonth($Month))."\n";
코드는 자명합니다.도움이 됐으면 좋겠네요
언급URL : https://stackoverflow.com/questions/1686724/how-to-find-the-last-day-of-the-month-from-date
'programing' 카테고리의 다른 글
MySQL 테이블에 인덱스를 추가하려면 어떻게 해야 합니까? (0) | 2022.11.27 |
---|---|
공백 공간을 언더스코어로 대체하려면 어떻게 해야 합니까? (0) | 2022.11.27 |
sql.쿼리가 잘리거나 불완전한 결과 (0) | 2022.11.27 |
딕트를 JSON 파일에 덤프하는 방법 (0) | 2022.11.27 |
브라우저 간 JavaScript(jQuery가 아님)를 스크롤하여 상단 애니메이션으로 이동합니다. (0) | 2022.11.27 |