[英]add days to month not exceeding last day of the month php
我有這個表格的日期 - - 20160428000000
(2016年4月28日)即yyyymmdd ...
我需要的是,如果某些日子(例如3)被添加到這個日期 - 它應該添加它們但不超過月份(04) - 預期產量 - 20160430000000
- 4月30日
同樣, 20160226000000
+ 5天應該返回20160229000000
即閏年2月。這意味着,它不應該跳到另一個月。
任何提示/想法?
另一種方法是使用DateTime
類來檢查它:
首先當然是通過輸入創建您的對象。 然后,設置月份對象的結束日期。
之后,進行添加,然后檢查它是否超過結束日期。 如果是,請將其設置為結尾,如果不是,則獲取添加的結果:
$day = 5; // days to be added
$date = '20160226000000'; // input date
$dt = DateTime::createFromFormat('YmdHis', $date); // create the input date
$end = clone $dt; // clone / copy the input
$end->modify('last day of this month'); // and set it to last day
$dt->add(DateInterval::createFromDateString("+{$day} days")); // add x days
// make comparision
$final_date = ($dt > $end) ? $end->format('YmdHis') : $dt->format('YmdHis');
echo $final_date;
為此你可以嘗試這樣:
$given_date = 20160428000000;
$no_of_day = 3;
if(date('m',strtotime($given_date)) < date('m',strtotime($given_date ." +".$no_of_day."days"))){
echo "Exceeded to next month <br/>";
echo "Last date of month should be: ".date("t M Y", strtotime($given_date));
}
else {
echo "Next date will be after ".$no_of_day." day(s)<br/>";
echo date('d M Y',strtotime($given_date ." +".$no_of_day."days"));
}
如果月份將跳到下個月,那么它將顯示當前月份的最后日期。 另外,它會在延長天數后顯示日期。
如果添加的日期超過最后一天,則會選擇最后一天作為新日期。
<?php
$date_orig = 20160226000000;
$add_day = 5; # No. of days to add
$added_date = strtotime($date_orig. ' + '.$add_day.' days'); // Add $add_day to $date_orig
$last_date = strtotime(date("YmtHis", strtotime($date_orig))); // Last day of $date_orig
$new_date = ($added_date > $last_date) ? $last_date : $added_date; // check the added date exceeds the last date
$new_date_format = date("YmdHis", $new_date); // Format Date
echo $new_date_format;
?>
<?php
$month_end = date('t-m-Y'); // Gets the last day of the month; e.g 31-07-2019
echo $month_end;
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.