Calculating week start/end dates for the next X weeks - php

I am trying to build a function in PHP that, depending on the date will give me
The current week (mon-sun) 20/8/12 to 26/8/12
Following week+1 (mon-sun) 27/8/12 to 02/9/12
Following week+2 (mon-sun) 03/9/12 to 09/9/12
Following week+3 (mon-sun)
Following week+4 (mon-sun)
Following week+5 (mon-sun)
I have tried using the following, but is there anything cleaner??
$week0_mon = date("Y-m-d", strtotime(date("Y").'W'.date('W')."1"));
$week0_sun = date("Y-m-d", strtotime(date("Y").'W'.date('W')."7"));
$week1_mon = date("Y-m-d", strtotime(date("Y-m-d", strtotime($week0_mon)) . " +1 week"));
$week1_sun = date("Y-m-d", strtotime(date("Y-m-d", strtotime($week0_sun)) . " +1 week"));
echo $week0_mon.' to '.$week0_sun.'<br />';
echo $week1_mon.' to '.$week1_sun.'<br />';

Maybe this will answer to your issue, it calculates the previous monday and start from here to add one week at a time. Just edit the for
$dOffsets = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
$prevMonday = mktime(0,0,0, date("m"), date("d")-array_search(date("l"),$dOffsets), date("Y"));
$oneWeek = 3600*24*7;$toSunday = 3600*24*6;
for ($i=0;$i<= 5;$i++)
{
echo "Week +",$i," (mon-sun) ",
date("d/m/Y",$prevMonday + $oneWeek*$i)," to ",
date("d/m/Y",$prevMonday + $oneWeek*$i + $toSunday),"<br>";
}
This gives me
Week +0 (mon-sun) 20/08/2012 to 26/08/2012
Week +1 (mon-sun) 27/08/2012 to 02/09/2012
Week +2 (mon-sun) 03/09/2012 to 09/09/2012
Week +3 (mon-sun) 10/09/2012 to 16/09/2012
Week +4 (mon-sun) 17/09/2012 to 23/09/2012
Week +5 (mon-sun) 24/09/2012 to 30/09/2012

I've adjusted #Wr1t3r answer to give correct date ranges as follows:
function plus_week($addWeek=0){
$last_monday_timestamp=strtotime('-'.(date('N')-1).' days');
if($addWeek!=0){
if($addWeek>0) $addWeek='+'.$addWeek;
$last_monday_timestamp=strtotime($addWeek.' week', $last_monday_timestamp);
}
$end_week_timestamp = strtotime ('+6 days', $last_monday_timestamp);
return date('d/m/y', $last_monday_timestamp).' to '.date('d/m/y', $end_week_timestamp);
}
date('N') will give weekday number mon-sun (1-7) so if we subtract 1 from this we know how many days to go back to last monday. OR we could have used strtotime('last monday').
BUT this way ensures we dont go back to last monday if we are currently on monday.
Monday=1 so (1-1=0) -0 days = today
Friday=5 so (5-1=4) -4 days = monday
SUNDAY=7 (not 0 if we used 'w') so (7-1=6) -6 days = monday (not tomorrow)
I've also adjusted this to do negative week numbers too.

I did it like this. I'm not sure if it is exactly what you want.
function plus_week($addWeek){
$date = date("d.m.Y",time());
$newdate = strtotime ( '+'.$addWeek.' week' , strtotime ( $date ) ) ;
$newdate = date ( 'd/m/y' , $newdate );
return $newdate;
}
for($i = 1; $i < 7; $i++){
echo "Following week+".$i." ".plus_week($i)." to ".plus_week($i+1)."<br/>";
}
From this you will get answer like this:
Following week+1 29/08/12 to 05/09/12
Following week+2 05/09/12 to 12/09/12
Following week+3 12/09/12 to 19/09/12
Following week+4 19/09/12 to 26/09/12
Following week+5 26/09/12 to 03/10/12
Following week+6 03/10/12 to 10/10/12

Related

strtotime('-1 month') returning wrong date if month have 31 days

I'm trying make a function to return the exact date of previous months.
That is a example of my code:
// Dates in TimeStamp
$ts_now = strtotime('now');
$ts_month1 = strtotime("-1 month", $ts_now);
$ts_month2 = strtotime("-2 month", $ts_now);
$ts_month3 = strtotime("-3 month", $ts_now);
// Dates Formated
$date_now = date('Y-m-d', $ts_now);
$date_month1 = date('Y-m-d', $ts_month1);
$date_month2 = date('Y-m-d', $ts_month2);
$date_month3 = date('Y-m-d', $ts_month3);
//Output
echo $date_now; //2020-04-30
echo $date_month1; //2020-03-30
echo $date_month2; //2020-03-01
echo $date_month3; //2020-01-30
The problem is in $date_month2 that represents February, the output is 2020-03-01 instead 2020-02-29 and I suppose that problem will happen in months who have 30 days when present date have 31 days.
What is the best way to resolve that?
As you can see working with the end of the month can be problematic because of how PHP works with dates. Your best bet is to go back to the beginning of the month, do your date math (i.e. go backwards in time), and then go to the date you want. That way you can check to see if the current day is greater than the number of days in month. If so, use the last day of the month instead.
function getMonthsAgo(int $n): string {
$date = new DateTime();
$day = $date->format('j');
$date->modify('first day of this month')->modify('-' . $n . ' months');
if ($day > $date->format('t')) {
$day = $date->format('t');
}
$date->setDate($date->format('Y'), $date->format('m'), $day);
return $date->format('Y-m-d');
}
// Dates Formated
$date_now = date('Y-m-d');
$date_month1 = getMonthsAgo(1);
$date_month2 = getMonthsAgo(2);
$date_month3 = getMonthsAgo(3);
//Output
echo $date_now;
echo $date_month1;
echo $date_month2;
echo $date_month3;
Output:
2020-04-30
2020-03-30
2020-02-29
2020-01-30

date() : First monday of first week of month?

I am actually trying to make a monthly reward system with a "stamp" interface.
For that, I want to use an HTML Table with 1 cell = 1 day, starting Monday.
Here is my problem (and the solution is probably easy to find !) : Monday isn't the first day of month - not for all month, atleast. How can I ask strtotime() & date() to show the date Y-m-d for :
"monday of first week of month" ?
"sunday of last week of month" ?
I'm expecting result like this for 2019-08 :
2019-07-29
2019-09-01
I did not find it on PHP Documentation but is there a way to place a third argument on date() to set up the date ?
Like that, I could have done something like this :
date('Y-m-d', strtotime('monday'), '2019-08-01');
EDIT :
Based on #Vidal answer here is what I tried, but I got a strange PHP reaction :
$first_date = date("Y-m-d", strtotime("first monday 2019-08 - 7 days"));
$last_date = date("Y-m-d", strtotime("last sunday 2019-09"));
$last_date2 = date("Y-m-d", strtotime("last sunday 2019-09 + 7 days"));
echo $first_date; ?><br>
echo $last_date; ?><br>
echo $last_date2; ?><br>
Output :
2019-07-29
2019-08-25
2019-09-08
I don't know why. Did you also notice that I need to set $last_date & $last_date2 to 2019-09 instead of 2019-08 ?
I think it's better to work with the DateTime object.
/*
I'm expecting result like this for 2019-08 :
"monday of first week of month" => 2019-07-29
"sunday of last week of month" => 2019-09-01
*/
$month = "2019-08";
$date = date_create($month."-02")
->modify("last Monday")
->format('l, d-m-Y')
;
echo $date."<br>";
$date = date_create("last Day of ".$month)
->modify("-1 Day")
->modify("next Sunday")
->format('l, d-m-Y')
;
echo $date."<br>";
/* Output
Monday, 29-07-2019
Sunday, 01-09-2019
*/
Do a loop for year, month.
echo date("j, d-M-Y", strtotime("first monday of 2019-08"));
echo date("j, d-M-Y", strtotime("last sunday of 2019-08"));
Hope it helps.
PHP Reference
I managed to make it work by changing some things to your code:
1) If the first monday is > 2 and <= 7, you have to remove 7 days to actually get the first monday
2) I added the '+ 7 days' on another line of code. It didn't work if I had 'last sunday of XXXX-XX + 7 days'
3) To get the last sunday based on your desired outputs, I compared the last sunday of the month with the total number of days in the month - 7. If it's bigger than that (25 for example), it means that it's not the last sunday
$year = 2019;
$month = 8;
if($month < 10)
$month = "0" . $month;
$currentDate = $year . "-" . $month;
if(date("d", strtotime("first monday of " . $currentDate)) > 2 && date("d", strtotime("first monday of " . $currentDate)) <= 7)
$first_date = date("Y-m-d", strtotime("first monday of " . $currentDate . " -7 days"));
else
$first_date = date("Y-m-d", strtotime("first monday of " . $currentDate));
if(date("d",strtotime("last sunday of " . $currentDate)) > date('t') - 7)
{
$last_date = date("Y-m-d", strtotime("last sunday of " . $currentDate));
$last_date = date("Y-m-d",strtotime($last_date . " +7 days")); //working when you add days like that. doesn't work if I put + 7 days in the 'last sunday of'...
}
else
$last_date = date("Y-m-d", strtotime("last sunday of " . $currentDate));
echo $first_date . "<br>";
echo $last_date . "<br>";

What is best solution to get next and previous month from given date php

I want to get next and previous month from given date. this is my code.
$month = '2011-01-20';
$prevMOnth = funP($month);
$nextMonth = funN($month);
what is best solution to do that.
$next_month_ts = strtotime('2011-01-20 +1 month');
$prev_month_ts = strtotime('2011-01-20 -1 month');
$next_month = date('Y-m-d', $next_month_ts);
$prev_month = date('Y-m-d', $prev_month_ts);
Code mentioned before might not work in the end of months with 31 day (or March):
$prev_month_ts = strtotime('2011-01-20 -1 month');
This is a best solution to get name of previous month. Get this month first day's date, then subtract 1 day, then get month name:
date('F', strtotime('-1 day', strtotime(date('Y-m-01'))));
And get name of next month. Get this month last day's date, then add 1 day, then get month name:
date('F', strtotime('+1 day', strtotime(date('Y-m-t'))));
don't know if it's the best way to do it, but it's built into php, check out strtotime
EDIT:
sample code
$month = '2011-01-20';
$timestamp = strtotime ("+1 month",strtotime ($month));
$nextMonth = date("Y-m-d",$timestamp);
$date = "2012-01-25";
$priormonth = date ('m', strtotime ( '-1 month' , strtotime ( $date )));
$futuremonth = date ('m', strtotime ( '+1 month' , strtotime ( $date )));
echo $priormonth; // this will equal 12
echo "<br/>";
echo $futuremonth; // this will equal 02
The '-1 month' solution is unreliable when the month has 31 days (like ALeX inSide mentioned).
Here is a function that returns the date of any desired number of months before a given date: (it returns actually the 1st day's date)
function getAnyPreviousMonthDate( $monthsBefore = null, $startDate = null )
{
$monthsBefore = $monthsBefore ?? 1; //php7
$monthsBefore = abs($monthsBefore);
$c = $startDate ?? date('Y-m-d');
for($i==0; $i<$monthsBefore; $i++) {
$c = date('Y-m-d', strtotime('first day of previous month '.$c));
}
return $c;
}
so if we calle this like:
echo getAnyPreviousMonthDate(3);
// we will get the first day of past 3 months from now
echo getAnyPreviousMonthDate(1, '2015-10-31');
// will return: '2015-09-01'

php - find date for same day of week for last year

So, in PHP i'm trying to return a date value for last year based on the same day of week.
EX: (Monday) 2011-12-19 inputted should return (Monday) 2010-12-20.
I was just doing it simply by -364 but then that was failing on leap years. I came across another function :
$newDate = $_POST['date'];
$newDate = strtotime($newDate);
$oldDate = strtotime('-1 year',$newDate);
$newDayOfWeek = date('w',$oldDate);
$oldDayOfWeek = date('w',$newDate);
$dayDiff = $oldDayOfWeek-$newDayOfWeek;
$oldDate = strtotime("$dayDiff days",$oldDate);
echo 'LAST YEAR DAY OF WEEK DATE = ' . date('Ymd', $oldDate);
however, that is failing when you try to input a Sunday date, as it does a 0 (sunday) minus 6 (saturday of last year date), and returns with a value T-6. IE inputting 2011-12-25 gets you 2010-12-19 instead of 2011-12-26.
I'm kind of stumped to find a good solution in php that will work for leap years and obviously all days of the week.
Any suggestions?
Thanks!
How about this, using PHP's DateTime functionality:
$date = new DateTime('2011-12-25'); // make a new DateTime instance with the starting date
$day = $date->format('l'); // get the name of the day we want
$date->sub(new DateInterval('P1Y')); // go back a year
$date->modify('next ' . $day); // from this point, go to the next $day
echo $date->format('Ymd'), "\n"; // ouput the date
$newDate = '2011-12-19';
date_default_timezone_set('UTC');
$newDate = strtotime($newDate);
$oldDate = strtotime('last year', $newDate);
$oldDate = strtotime(date('l', $newDate), $oldDate);
$dateFormat = 'Y-m-d l w W';
echo "This date: ", date($dateFormat, $newDate), "\n";
echo "Old date : ", date($dateFormat, $oldDate);
That gives:
This date: 2011-12-19 Monday 1 51
Old date : 2010-12-20 Monday 1 51
Use strtotime() to get a date, for the same week last year.
Use the format {$year}-W{$week}-{$weekday}, like this:
echo date("Y-m-d", strtotime("2010-W12-1"));
And you can do that for as long back you wan't:
<?php
for($i = 2011; $i > 2000; $i--)
echo date("Y-m-d", strtotime($i."-W12-1"));
?>
Make it easier :)
echo date('Y-m-d (l, W)').<br/>;
echo date('Y-m-d (l, W)', strtotime("-52 week"));
Edit: I forgot to write output: :)
2015-05-06 (Wednesday, 19)
2014-05-07 (Wednesday, 19)
<?php
$date = "2020-01-11";
$newdate = date("Y-m-d",strtotime ( '-1 year' , strtotime ( $date ) )) ;
echo $newdate;
?>
ref https://www.nicesnippets.com/blog/how-to-get-previous-year-from-date-in-php

increment date by one month

Let's say I have a date in the following format: 2010-12-11 (year-mon-day)
With PHP, I want to increment the date by one month, and I want the year to be automatically incremented, if necessary (i.e. incrementing from December 2012 to January 2013).
Regards.
$time = strtotime("2010.12.11");
$final = date("Y-m-d", strtotime("+1 month", $time));
// Finally you will have the date you're looking for.
I needed similar functionality, except for a monthly cycle (plus months, minus 1 day). After searching S.O. for a while, I was able to craft this plug-n-play solution:
function add_months($months, DateTime $dateObject)
{
$next = new DateTime($dateObject->format('Y-m-d'));
$next->modify('last day of +'.$months.' month');
if($dateObject->format('d') > $next->format('d')) {
return $dateObject->diff($next);
} else {
return new DateInterval('P'.$months.'M');
}
}
function endCycle($d1, $months)
{
$date = new DateTime($d1);
// call second function to add the months
$newDate = $date->add(add_months($months, $date));
// goes back 1 day from date, remove if you want same day of month
$newDate->sub(new DateInterval('P1D'));
//formats final date to Y-m-d form
$dateReturned = $newDate->format('Y-m-d');
return $dateReturned;
}
Example:
$startDate = '2014-06-03'; // select date in Y-m-d format
$nMonths = 1; // choose how many months you want to move ahead
$final = endCycle($startDate, $nMonths); // output: 2014-07-02
Use DateTime::add.
$start = new DateTime("2010-12-11", new DateTimeZone("UTC"));
$month_later = clone $start;
$month_later->add(new DateInterval("P1M"));
I used clone because add modifies the original object, which might not be desired.
strtotime( "+1 month", strtotime( $time ) );
this returns a timestamp that can be used with the date function
You can use DateTime::modify like this :
$date = new DateTime('2010-12-11');
$date->modify('+1 month');
See documentations :
https://php.net/manual/en/datetime.modify.php
https://php.net/manual/en/class.datetime.php
UPDATE january 2021 : correct mistakes raised by comments
This solution has some problems for months with 31 days like May etc.
Exemple : this jumps from 31st May to 1st July which is incorrect.
To correct that, you can create this custom function
function addMonths($date,$months){
$init=clone $date;
$modifier=$months.' months';
$back_modifier =-$months.' months';
$date->modify($modifier);
$back_to_init= clone $date;
$back_to_init->modify($back_modifier);
while($init->format('m')!=$back_to_init->format('m')){
$date->modify('-1 day') ;
$back_to_init= clone $date;
$back_to_init->modify($back_modifier);
}
}
Then you can use it like that :
$date = new DateTime('2010-05-31');
addMonths($date, 1);
print_r($date);
//DateTime Object ( [date] => 2010-06-30 00:00:00.000000 [timezone_type] => 3 [timezone] => Europe/Berlin )
This solution was found in PHP.net posted by jenspj : https://www.php.net/manual/fr/datetime.modify.php#107592
(date('d') > 28) ? date("mdY", strtotime("last day of next month")) : date("mdY", strtotime("+1 month"));
This will compensate for February and the other 31 day months. You could of course do a lot more checking to to get more exact for 'this day next month' relative date formats (which does not work sadly, see below), and you could just as well use DateTime.
Both DateInterval('P1M') and strtotime("+1 month") are essentially blindly adding 31 days regardless of the number of days in the following month.
2010-01-31 => March 3rd
2012-01-31 => March 2nd (leap year)
Please first you set your date format as like 12-12-2012
After use this function it's work properly;
$date = date('d-m-Y',strtotime("12-12-2012 +2 Months");
Here 12-12-2012 is your date and +2 Months is increment of the month;
You also increment of Year, Date
strtotime("12-12-2012 +1 Year");
Ans is 12-12-2013
I use this way:-
$occDate='2014-01-28';
$forOdNextMonth= date('m', strtotime("+1 month", strtotime($occDate)));
//Output:- $forOdNextMonth=02
/*****************more example****************/
$occDate='2014-12-28';
$forOdNextMonth= date('m', strtotime("+1 month", strtotime($occDate)));
//Output:- $forOdNextMonth=01
//***********************wrong way**********************************//
$forOdNextMonth= date('m', strtotime("+1 month", $occDate));
//Output:- $forOdNextMonth=02; //instead of $forOdNextMonth=01;
//******************************************************************//
Just updating the answer with simple method for find the date after no of months. As the best answer marked doesn't give the correct solution.
<?php
$date = date('2020-05-31');
$current = date("m",strtotime($date));
$next = date("m",strtotime($date."+1 month"));
if($current==$next-1){
$needed = date('Y-m-d',strtotime($date." +1 month"));
}else{
$needed = date('Y-m-d', strtotime("last day of next month",strtotime($date)));
}
echo "Date after 1 month from 2020-05-31 would be : $needed";
?>
If you want to get the date of one month from now you can do it like this
echo date('Y-m-d', strtotime('1 month'));
If you want to get the date of two months from now, you can achieve that by doing this
echo date('Y-m-d', strtotime('2 month'));
And so on, that's all.
Thanks Jason, your post was very helpful. I reformatted it and added more comments to help me understand it all. In case that helps anyone, I have posted it here:
function cycle_end_date($cycle_start_date, $months) {
$cycle_start_date_object = new DateTime($cycle_start_date);
//Find the date interval that we will need to add to the start date
$date_interval = find_date_interval($months, $cycle_start_date_object);
//Add this date interval to the current date (the DateTime class handles remaining complexity like year-ends)
$cycle_end_date_object = $cycle_start_date_object->add($date_interval);
//Subtract (sub) 1 day from date
$cycle_end_date_object->sub(new DateInterval('P1D'));
//Format final date to Y-m-d
$cycle_end_date = $cycle_end_date_object->format('Y-m-d');
return $cycle_end_date;
}
//Find the date interval we need to add to start date to get end date
function find_date_interval($n_months, DateTime $cycle_start_date_object) {
//Create new datetime object identical to inputted one
$date_of_last_day_next_month = new DateTime($cycle_start_date_object->format('Y-m-d'));
//And modify it so it is the date of the last day of the next month
$date_of_last_day_next_month->modify('last day of +'.$n_months.' month');
//If the day of inputted date (e.g. 31) is greater than last day of next month (e.g. 28)
if($cycle_start_date_object->format('d') > $date_of_last_day_next_month->format('d')) {
//Return a DateInterval object equal to the number of days difference
return $cycle_start_date_object->diff($date_of_last_day_next_month);
//Otherwise the date is easy and we can just add a month to it
} else {
//Return a DateInterval object equal to a period (P) of 1 month (M)
return new DateInterval('P'.$n_months.'M');
}
}
$cycle_start_date = '2014-01-31'; // select date in Y-m-d format
$n_months = 1; // choose how many months you want to move ahead
$cycle_end_date = cycle_end_date($cycle_start_date, $n_months); // output: 2014-07-02
function dayOfWeek($date){
return DateTime::createFromFormat('Y-m-d', $date)->format('N');
}
Usage examples:
echo dayOfWeek(2016-12-22);
// "4"
echo dayOfWeek(date('Y-m-d'));
// "4"
$date = strtotime("2017-12-11");
$newDate = date("Y-m-d", strtotime("+1 month", $date));
If you want to increment by days you can also do it
$date = strtotime("2017-12-11");
$newDate = date("Y-m-d", strtotime("+5 day", $date));
For anyone looking for an answer to any date format.
echo date_create_from_format('d/m/Y', '15/04/2017')->add(new DateInterval('P1M'))->format('d/m/Y');
Just change the date format.
//ECHO MONTHS BETWEEN TWO TIMESTAMPS
$my_earliest_timestamp = 1532095200;
$my_latest_timestamp = 1554991200;
echo '<pre>';
echo "Earliest timestamp: ". date('c',$my_earliest_timestamp) ."\r\n";
echo "Latest timestamp: " .date('c',$my_latest_timestamp) ."\r\n\r\n";
echo "Month start of earliest timestamp: ". date('c',strtotime('first day of '. date('F Y',$my_earliest_timestamp))) ."\r\n";
echo "Month start of latest timestamp: " .date('c',strtotime('first day of '. date('F Y',$my_latest_timestamp))) ."\r\n\r\n";
echo "Month end of earliest timestamp: ". date('c',strtotime('last day of '. date('F Y',$my_earliest_timestamp)) + 86399) ."\r\n";
echo "Month end of latest timestamp: " .date('c',strtotime('last day of '. date('F Y',$my_latest_timestamp)) + 86399) ."\r\n\r\n";
$sMonth = strtotime('first day of '. date('F Y',$my_earliest_timestamp));
$eMonth = strtotime('last day of '. date('F Y',$my_earliest_timestamp)) + 86399;
$xMonth = strtotime('+1 month', strtotime('first day of '. date('F Y',$my_latest_timestamp)));
while ($eMonth < $xMonth) {
echo "Things from ". date('Y-m-d',$sMonth) ." to ". date('Y-m-d',$eMonth) ."\r\n\r\n";
$sMonth = $eMonth + 1; //add 1 second to bring forward last date into first second of next month.
$eMonth = strtotime('last day of '. date('F Y',$sMonth)) + 86399;
}
I find the mtkime() function works really well for this:
$start_date="2021-10-01";
$start_date_plus_a_month=date("Y-m-d", mktime(0, 0, 0, date("m",strtotime($start_date))+1, date("d",strtotime($start_date)), date("Y",strtotime($start_date))));
result: 2021-11-01
I like to subtract 1 from the 'day' to produce '2021-10-31' which can be useful if you want to display a range across 12 months, e.g. Oct 1, 2021 to Sep 30 2022
$start_date_plus_a_year=date("Y-m-d", mktime(0, 0, 0, date("m",strtotime($start_date))+12, date("d",strtotime($start_date))-1, date("Y",strtotime($start_date))));
result: 2022-09-30
The correct answer to the exact question asked is Giuseppe Canale's answer from earlier. I'm going to answer a slightly more generic question of how to increment the date by an arbitrary number of months, however.
<?php
/**
* Will return a timestamp corresponding to first day of the month that is N months into the future.
* #param int $months_later number of months into the future: 0 for current one
* #param string $today if supplied will be used as the "now" time
* #return int
*/
function rel_month_to_time($months_later, $today=null) {
if ($months_later===0) {
return is_null($today) ? time() : strtotime($today);
}
return strtotime('first day of next month', rel_month_to_time($months_later-1, $today));
}
As is many times the case, you can use recursion for these "human problems" like calendars. The above can be used to return a timestamp corresponding to "next month" -- the way we humans think of it.
<?php echo date('Y-m-d', rel_month_to_time(1, '2023-01-30'));
// 2023-02-01
As pointed by #NetVicious i corrected the code, it should work with all dates, some example:
2013-01-30 will be 2013-02-28
2013-05-15 will be 2013-05-15
2013-05-31 will be 2013-06-30
This code uses the DateTime class to create a new date object, then it adds 1 month to the date using the modify method. Next, it gets the day of the next month using the format method. If the next month's day doesn't match the original day, it modifies the date to the last day of the previous month using the modify method.
$original_date = "2013-01-30";
$original_day = date("d", strtotime($original_date));
$date = new DateTime($original_date);
$date->modify('+1 month');
$next_month_day = $date->format('d');
if ($next_month_day != $original_day) {
$date->modify('last day of previous month');
}
$new_date = $date->format('Y-m-d');
echo $new_date;
All presented solutions are not working properly.
strtotime() and DateTime::add or DateTime::modify give sometime invalid results.
Examples:
- 31.08.2019 + 1 month gives 01.10.2019 instead 30.09.2019
- 29.02.2020 + 1 year gives 01.03.2021 instead 28.02.2021
(tested on PHP 5.5, PHP 7.3)
Below is my function based on idea posted by Angelo that solves the problem:
// $time - unix time or date in any format accepted by strtotime() e.g. 2020-02-29
// $days, $months, $years - values to add
// returns new date in format 2021-02-28
function addTime($time, $days, $months, $years)
{
// Convert unix time to date format
if (is_numeric($time))
$time = date('Y-m-d', $time);
try
{
$date_time = new DateTime($time);
}
catch (Exception $e)
{
echo $e->getMessage();
exit;
}
if ($days)
$date_time->add(new DateInterval('P'.$days.'D'));
// Preserve day number
if ($months or $years)
$old_day = $date_time->format('d');
if ($months)
$date_time->add(new DateInterval('P'.$months.'M'));
if ($years)
$date_time->add(new DateInterval('P'.$years.'Y'));
// Patch for adding months or years
if ($months or $years)
{
$new_day = $date_time->format("d");
// The day is changed - set the last day of the previous month
if ($old_day != $new_day)
$date_time->sub(new DateInterval('P'.$new_day.'D'));
}
// You can chage returned format here
return $date_time->format('Y-m-d');
}
Usage examples:
echo addTime('2020-02-29', 0, 0, 1); // add 1 year (result: 2021-02-28)
echo addTime('2019-08-31', 0, 1, 0); // add 1 month (result: 2019-09-30)
echo addTime('2019-03-15', 12, 2, 1); // add 12 days, 2 months, 1 year (result: 2019-09-30)
put a date in input box then click the button get day from date in jquery
$(document).ready( function() {
$("button").click(function(){
var day = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var a = new Date();
$(".result").text(day[a.getDay()]);
});
});
<?php
$selectdata ="select fromd,tod from register where username='$username'";
$q=mysqli_query($conm,$selectdata);
$row=mysqli_fetch_array($q);
$startdate=$row['fromd'];
$stdate=date('Y', strtotime($startdate));
$endate=$row['tod'];
$enddate=date('Y', strtotime($endate));
$years = range ($stdate,$enddate);
echo '<select name="years" class="form-control">';
echo '<option>SELECT</option>';
foreach($years as $year)
{ echo '<option value="'.$year.'"> '.$year.' </option>'; }
echo '</select>'; ?>

Categories