简体   繁体   中英

add days to month not exceeding last day of the month php

I have date in this form - - 20160428000000 (28th April 2016) ie yyyymmdd...

I need that if some days(eg. 3) are added to this date - it should add them but not exceed the month(04) - expected output - 20160430000000 - 30th April

Similarly, 20160226000000 + 5days should return 20160229000000 ie leap year Feb. That means, it should not jump to another month.

Any hints/Ideas ?

Another alternative would be to use DateTime classes to check it out:

First of course create your object thru the input. Then, set the ending day of the month object.

After that, make the addition then check if it exceeds the ending day. If yes, set it to the end, if not, then get the result of the addition:

$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;

For this you can try like this:

$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"));
}

If month will jump to next month then it will show the current month last date. other wise it will show date after number of days extended.

If the added date exceeds last day, will select the last day as the new date.

<?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;
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM