Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have date in this form - - 20160428000000 (28th April 2016) i.e 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 i.e leap year Feb. That means, it should not jump to another month.

Any hints/Ideas ?

like image 948
jitendrapurohit Avatar asked Apr 15 '16 06:04

jitendrapurohit


1 Answers

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;
like image 83
Kevin Avatar answered Sep 28 '22 04:09

Kevin