Get the date of next monday, tuesday, etc - php

I would like to find the date stamp of monday, tuesday, wednesday, etc. If that day hasn't come this week yet, I would like the date to be this week, else, next week. Thanks!

See strtotime()
strtotime('next tuesday');
You could probably find out if you have gone past that day by looking at the week number:
$nextTuesday = strtotime('next tuesday');
$weekNo = date('W');
$weekNoNextTuesday = date('W', $nextTuesday);
if ($weekNoNextTuesday != $weekNo) {
//past tuesday
}

I know it's a bit of a late answer but I would like to add my answer for future references.
// Create a new DateTime object
$date = new DateTime();
// Modify the date it contains
$date->modify('next monday');
// Output
echo $date->format('Y-m-d');
The nice thing is that you can also do this with dates other than today:
// Create a new DateTime object
$date = new DateTime('2006-05-20');
// Modify the date it contains
$date->modify('next monday');
// Output
echo $date->format('Y-m-d');
To make the range:
$monday = new DateTime('monday');
// clone start date
$endDate = clone $monday;
// Add 7 days to start date
$endDate->modify('+7 days');
// Increase with an interval of one day
$dateInterval = new DateInterval('P1D');
$dateRange = new DatePeriod($monday, $dateInterval, $endDate);
foreach ($dateRange as $day) {
echo $day->format('Y-m-d')."<br />";
}
References
PHP Manual - DateTime
PHP Manual - DateInterval
PHP Manual - DatePeriod
PHP Manual - clone

The question is tagged "php" so as Tom said, the way to do that would look like this:
date('Y-m-d', strtotime('next tuesday'));

For some reason, strtotime('next friday') display the Friday date of the current week. Try this instead:
//Current date 2020-02-03
$fridayNextWeek = date('Y-m-d', strtotime('friday next week'); //Outputs 2020-02-14
$nextFriday = date('Y-m-d', strtotime('next friday'); //Outputs 2020-02-07

You can use Carbon library.
Example: Next week friday
Carbon::parse("friday next week");

PHP 7.1:
$next_date = new DateTime('next Thursday');
$stamp = $next_date->getTimestamp();
PHP manual getTimestamp()

Sorry, I didn't notice the PHP tag - however someone else might be interested in a VB solution:
Module Module1
Sub Main()
Dim d As Date = Now
Dim nextFriday As Date = DateAdd(DateInterval.Weekday, DayOfWeek.Friday - d.DayOfWeek(), Now)
Console.WriteLine("next friday is " & nextFriday)
Console.ReadLine()
End Sub
End Module

If I understand you correctly, you want the dates of the next 7 days?
You could do the following:
for ($i = 0; $i < 7; $i++)
echo date('d/m/y', time() + 86400 * $i);
Check the documentation for the date function for the format you want it in.

if you want to find Monday then 'dayOfWeek' is 1 if it is Tuesday it will be 2 and so on.
var date=new Date();
getNextDayOfWeek(date, 2);
// this is for finding next tuesday
function getNextDayOfWeek(date, dayOfWeek) {
// Code to check that date and dayOfWeek are valid left as an exercise ;)
var resultDate = new Date(date.getTime());
resultDate.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7);
return resultDate;
}
Hope this will be helpfull to you, thank you

The PHP documentation for time() shows an example of how you can get a date one week out. You can modify this to instead go into a loop that iterates a maximum of 7 times, get the timestamp each time, get the corresponding date, and from that get the day of the week.

Related

PHP Date: get every Friday at specific hour [duplicate]

I would like to find the date stamp of monday, tuesday, wednesday, etc. If that day hasn't come this week yet, I would like the date to be this week, else, next week. Thanks!
See strtotime()
strtotime('next tuesday');
You could probably find out if you have gone past that day by looking at the week number:
$nextTuesday = strtotime('next tuesday');
$weekNo = date('W');
$weekNoNextTuesday = date('W', $nextTuesday);
if ($weekNoNextTuesday != $weekNo) {
//past tuesday
}
I know it's a bit of a late answer but I would like to add my answer for future references.
// Create a new DateTime object
$date = new DateTime();
// Modify the date it contains
$date->modify('next monday');
// Output
echo $date->format('Y-m-d');
The nice thing is that you can also do this with dates other than today:
// Create a new DateTime object
$date = new DateTime('2006-05-20');
// Modify the date it contains
$date->modify('next monday');
// Output
echo $date->format('Y-m-d');
To make the range:
$monday = new DateTime('monday');
// clone start date
$endDate = clone $monday;
// Add 7 days to start date
$endDate->modify('+7 days');
// Increase with an interval of one day
$dateInterval = new DateInterval('P1D');
$dateRange = new DatePeriod($monday, $dateInterval, $endDate);
foreach ($dateRange as $day) {
echo $day->format('Y-m-d')."<br />";
}
References
PHP Manual - DateTime
PHP Manual - DateInterval
PHP Manual - DatePeriod
PHP Manual - clone
The question is tagged "php" so as Tom said, the way to do that would look like this:
date('Y-m-d', strtotime('next tuesday'));
For some reason, strtotime('next friday') display the Friday date of the current week. Try this instead:
//Current date 2020-02-03
$fridayNextWeek = date('Y-m-d', strtotime('friday next week'); //Outputs 2020-02-14
$nextFriday = date('Y-m-d', strtotime('next friday'); //Outputs 2020-02-07
You can use Carbon library.
Example: Next week friday
Carbon::parse("friday next week");
PHP 7.1:
$next_date = new DateTime('next Thursday');
$stamp = $next_date->getTimestamp();
PHP manual getTimestamp()
Sorry, I didn't notice the PHP tag - however someone else might be interested in a VB solution:
Module Module1
Sub Main()
Dim d As Date = Now
Dim nextFriday As Date = DateAdd(DateInterval.Weekday, DayOfWeek.Friday - d.DayOfWeek(), Now)
Console.WriteLine("next friday is " & nextFriday)
Console.ReadLine()
End Sub
End Module
If I understand you correctly, you want the dates of the next 7 days?
You could do the following:
for ($i = 0; $i < 7; $i++)
echo date('d/m/y', time() + 86400 * $i);
Check the documentation for the date function for the format you want it in.
if you want to find Monday then 'dayOfWeek' is 1 if it is Tuesday it will be 2 and so on.
var date=new Date();
getNextDayOfWeek(date, 2);
// this is for finding next tuesday
function getNextDayOfWeek(date, dayOfWeek) {
// Code to check that date and dayOfWeek are valid left as an exercise ;)
var resultDate = new Date(date.getTime());
resultDate.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7);
return resultDate;
}
Hope this will be helpfull to you, thank you
The PHP documentation for time() shows an example of how you can get a date one week out. You can modify this to instead go into a loop that iterates a maximum of 7 times, get the timestamp each time, get the corresponding date, and from that get the day of the week.

php add x weeks to a date and then find the next given day

I can add x week to my date
//$ultima_azione <--- 2015/07/15
//$data['intervallo'] <---- 5
$mydate = date("Y-m-d",strtotime($ultima_azione." +".$data['intervallo']." weeks"));
now how can i give a day starting from that week
example:
//$mydate + "next Monday" -----> final date
and this ve to work like, if today is Monday and i add weeks to jump to an other Monday and then i select the next Monday the week don't ve to change
The simplest way would be to use strtotime. It can do date calculations based on a textual representation of the delta:
$mydate = strtotime('+3 weeks');
It also accepts a second parameter, which is a timestamp to start from when doing the calculation, so after you get the offset in weeks, you can pass the new date to a second calculation:
// Get three weeks from 'now' (no explicit time given)
$mydate = strtotime('+3 weeks');
// Get the Monday after that.
$mydate = strtotime('next Monday', $mydate);
See strtotime documentation for more examples of notations that you can use.
I would highly recommend using PHP's built-in DateTime class for any date and time logic. It's a much better API than the older date and time functions and creates much cleaner and easier to read code.
For example:
// Current date and number of weeks to add
$date = '2015/07/15';
$weeks = 3;
// Create and modify the date.
$dateTime = DateTime::createFromFormat('Y/m/d', $date);
$dateTime->add(DateInterval::createFromDateString($weeks . ' weeks'));
$dateTime->modify('next monday');
// Output the new date.
echo $dateTime->format('Y-m-d');
References:
DateTime.
DateTime::createFromFormat
DateTime::add
DateTime::modify
DateInterval::createFromDateString
DateTime::format
Are you looking for something like this?
$today = time();
$weeks = 2;
// timestamp 2 weeks from now
$futureWeeks = strtotime("+ ".$weeks." weeks");
// the next monday after the timestamp date
$futureMonday = strtotime("next monday",$futureWeeks);
echo date("Y-m-d", $futureMonday);
// or in one line
echo date("Y-m-d", strtotime("next monday", strtotime("+ ".$weeks." weeks")));
PHP is using an unix timestamp for date calculations. Functions as date() and strtotime() using a timestamp as an optional second parameter. This is used a reference for formatting and calculations. If no timestamp is passed to the function the current timestamp is used (time()).
I have the answer here. This will show the next wednesday every 2 weeks and the first date to start from would be the 10th.
I have also added in an estimated delivery which would be 6 weeks after that date.
We will be placing our next order for this on:
<?php
$date = '2020/05/26';
$weeks = 2;
$dateTime = DateTime::createFromFormat('Y/m/d', $date);
$dateTime->add(DateInterval::createFromDateString($weeks . ' weeks'));
$dateTime->modify('wednesday');
echo $dateTime->format('d/m/Y');
?>
Expected delivery for the next order will be:
<?php
$date = '2020/05/26';
$weeks = 2;
$dateTime = DateTime::createFromFormat('Y/m/d', $date);
$dateTime->add(DateInterval::createFromDateString($weeks . ' weeks'));
$dateTime->modify('+42 days next wednesday');
echo $dateTime->format('d/m/Y');
?>
If anyone can confirm this is correct that would be great.

Getting first / last date of the week

Is it possible to get the first / last date of a week using PHP's Relative Date Time format?
I've tried to do:
date_default_timezone_set('Europe/Amsterdam');
$date = new DateTime();
$date->modify('first day of this week'); // to get the current week's first date
echo $date->format('Y-m-d'); // outputs 2011-12-19
$date->modify('first day of week 50'); // to get the first date of any week by weeknumber
echo $date->format('Y-m-d'); // outputs 2011-12-18
$date->modify('last day of this week'); // to get the current week's last date
echo $date->format('Y-m-d'); // outputs 2011-12-17
$date->modify('last day of week 50'); // to get the last date of any week by weeknumber
echo $date->format('Y-m-d'); // outputs 2011-12-18
As you can see it doesn't output the correct dates.
According to the docs this should be possible if I'm correct.
Am I doing something terrible wrong?
EDIT
I need to use PHP's DateTime for dates in the far future.
UPDATE
It gets only stranger now. I've done some more testing.
Windows PHP 5.3.3
2011-12-01
Warning: DateTime::modify() [datetime.modify]: Failed to parse time string (first day of week 50) at position 13 (w): The timezone could not be found in the database in C:\Users\Gerrie\Desktop\ph\Websites\Charts\www.charts.com\public\index.php on line 9
2011-12-01
2011-11-30
Warning: DateTime::modify() [datetime.modify]: Failed to parse time string (last day of week 50) at position 12 (w): The timezone could not be found in the database in C:\Users\Gerrie\Desktop\ph\Websites\Charts\www.charts.com\public\index.php on line 15
2011-11-30
Linux 5.3.8
2011-12-01
2011-12-01
2011-11-30
2011-11-30
I'm a big fan of using the Carbon library, which makes this sort of thing really easy. For example:
use Carbon\Carbon;
$monday = Carbon::now()->startOfWeek()
$sunday = Carbon::now()->endOfWeek()
Or, if you'd prefer to have Sunday be the first day of your week:
use Carbon\Carbon;
Carbon::setWeekStartsAt(Carbon::SUNDAY);
Carbon::setWeekEndsAt(Carbon::SATURDAY);
$sunday = Carbon::now()->startOfWeek()
$saturday = Carbon::now()->endOfWeek()
According to docs the format strings "first day of" and "last day of" are only allowed for months, not for weeks. See http://www.php.net/manual/en/datetime.formats.relative.php
If you combine first and last day of with a week statement the result either blows the parser or is something that you did not expect (usually the first or last day of a month, not a week).
The difference that you see between Win and Linux is probably only because of different error reporting settings.
To get the first and last day of the current week use:
$date->modify('this week');
$date->modify('this week +6 days');
To get the first and last day of week 50 use:
$date->setISODate(2011, 50);
$date->setISODate(2011, 50, 7);
EDIT:
If you want to use the modify method for absolute week numbers you have to use the formats defined in http://www.php.net/manual/en/datetime.formats.compound.php:
$date->modify('2011W50');
$date->modify('2011W50 +6 days');
if first day of week is Monday
$date->modify('Monday this week');
else if first day is Sunday
$date->modify('Sunday this week');
because in different countries first day of week maybe Monday or Sunday
This is what I am using to get the first and last day of the week from any date.
In this case, monday is the first day of the week...
$date = date('Y-m-d'); // you can put any date you want
$nbDay = date('N', strtotime($date));
$monday = new DateTime($date);
$sunday = new DateTime($date);
$monday->modify('-'.($nbDay-1).' days');
$sunday->modify('+'.(7-$nbDay).' days');
function getweek_first_last_date($date)
{
$cur_date = strtotime($date); // Change to whatever date you need
// Get the day of the week: Sunday = 0 to Saturday = 6
$dotw = date('w', $cur_date);
if($dotw>1)
{
$pre_monday = $cur_date-(($dotw-1)*24*60*60);
$next_sunday = $cur_date+((7-$dotw)*24*60*60);
}
else if($dotw==1)
{
$pre_monday = $cur_date;
$next_sunday = $cur_date+((7-$dotw)*24*60*60);
}
else if($dotw==0)
{
$pre_monday =$cur_date -(6*24*60*60);;
$next_sunday = $cur_date;
}
$date_array = array();
$date_array['start_date_of_week'] = $pre_monday;
$date_array['end_date_of_week'] = $next_sunday;
return $date_array;
}
$date = '2013-12-22';
getweek_first_last_date($date);
Output :
$array_of_week = Array
(
[start_date_of_week] => 1387152000
[end_date_of_week] => 1387670400
)
$start_date =date('d/m/Y', $array_of_week['start_date_of_week'])
<code>
function getlastweek_first_last_date()
{
$cur_date = strtotime(date('Y-m-d')); // Change to whatever date you need
// Get the day of the week: Sunday = 0 to Saturday = 6
$previousweekcurdate = $cur_date - (7*24*3600);
$cur_date = $previousweekcurdate;
$dotw = date('w', $cur_date);
if($dotw>1)
{
$pre_sunday = $cur_date-(($dotw-1)*24*60*60) - (24*60*60);
$next_satday = $cur_date+((7-$dotw)*24*60*60)- (24*60*60);
}
else if($dotw==1)
{
$pre_sunday = $cur_date- (24*60*60);
$next_satday = $cur_date+((7-$dotw)*24*60*60)- (24*60*60);
}
else if($dotw==0)
{
$pre_sunday =$cur_date -(6*24*60*60)- (24*60*60);
$next_satday = $cur_date- (24*60*60);
}
$pre_sunday = date('Y-m-d',$pre_sunday)." 00:00:00";
$next_satday = date('Y-m-d',$next_satday)." 23:59:59";
$date_array = array();
$date_array['sdoflw'] = $pre_sunday;
$date_array['edoflw'] = $next_satday;
return $date_array;
}
$date_array = getlastweek_first_last_date();
echo $start_date_of_week = $date_array['sdoflw'];
echo $end_date_of_week = $date_array['edoflw'];
</code>
Simply you can get the date as follows
first day of week is Monday
date('Y-m-d',strtotime('Monday this week'));
if first day is Sunday
date('Y-m-d',strtotime('Sunday this week'));

PHP get start and end date of a week by weeknumber

I've seen some variants on this question but I believe this one hasn't been answered yet.
I need to get the starting date and ending date of a week, chosen by year and week number (not a date)
example:
input:
getStartAndEndDate($week, $year);
output:
$return[0] = $firstDay;
$return[1] = $lastDay;
The return value will be something like an array in which the first entry is the week starting date and the second being the ending date.
OPTIONAL: while we are at it, the date format needs to be Y-n-j (normal date format, no leading zeros.
I've tried editing existing functions that almost did what I wanted but I had no luck so far.
Using DateTime class:
function getStartAndEndDate($week, $year) {
$dto = new DateTime();
$dto->setISODate($year, $week);
$ret['week_start'] = $dto->format('Y-m-d');
$dto->modify('+6 days');
$ret['week_end'] = $dto->format('Y-m-d');
return $ret;
}
$week_array = getStartAndEndDate(52,2013);
print_r($week_array);
Returns:
Array
(
[week_start] => 2013-12-23
[week_end] => 2013-12-29
)
Explained:
Create a new DateTime object which defaults to now()
Call setISODate to change object to first day of $week of $year instead of now()
Format date as 'Y-m-d' and put in $ret['week_start']
Modify the object by adding 6 days, which will be the end of $week
Format date as 'Y-m-d' and put in $ret['week_end']
A shorter version (works in >= php5.3):
function getStartAndEndDate($week, $year) {
$dto = new DateTime();
$ret['week_start'] = $dto->setISODate($year, $week)->format('Y-m-d');
$ret['week_end'] = $dto->modify('+6 days')->format('Y-m-d');
return $ret;
}
Could be shortened with class member access on instantiation in >= php5.4.
Many years ago, I found this function:
function getStartAndEndDate($week, $year) {
$dto = new DateTime();
$dto->setISODate($year, $week);
$ret['week_start'] = $dto->format('Y-m-d');
$dto->modify('+6 days');
$ret['week_end'] = $dto->format('Y-m-d');
return $ret;
}
$week_array = getStartAndEndDate(52,2013);
print_r($week_array);
We can achieve this easily without the need for extra computations apart from those inherent to the DateTime class.
function getStartAndEndDate($year, $week)
{
return [
(new DateTime())->setISODate($year, $week)->format('Y-m-d'), //start date
(new DateTime())->setISODate($year, $week, 7)->format('Y-m-d') //end date
];
}
The setISODate() function takes three arguments: $year, $week, and $day respectively, where $day defaults to 1 - the first day of the week. We therefore pass 7 to get the exact date of the 7th day of the $week.
Slightly neater solution, using the "[year]W[week][day]" strtotime format:
function getStartAndEndDate($week, $year) {
// Adding leading zeros for weeks 1 - 9.
$date_string = $year . 'W' . sprintf('%02d', $week);
$return[0] = date('Y-n-j', strtotime($date_string));
$return[1] = date('Y-n-j', strtotime($date_string . '7'));
return $return;
}
shortest way to do it:
function week_date($week, $year){
$date = new DateTime();
return "first day of the week is ".$date->setISODate($year, $week, "1")->format('Y-m-d')
."and last day of the week is ".$date->setISODate($year, $week, "7")->format('Y-m-d');
}
echo week_date(12,2014);
You can get the specific day of week from date as bellow that I get the first and last day
$date = date_create();
// get the first day of the week
date_isodate_set($date, 2019, 1);
//convert date format and show
echo date_format($date, 'Y-m-d') . "\n";
// get the last date of the week
date_isodate_set($date, 2019, 1, 7);
//convert date format and show
echo date_format($date, 'Y-m-d') . "\n";
Output =>
2018-12-31
2019-01-06
The calculation of Roham Rafii is wrong. Here is a short solution:
// week number to timestamp (first day of week number)
function wn2ts($week, $year) {
return strtotime(sprintf('%dW%02d', $year, $week));
}
if you want the last day of the week number, you can add up 6 * 24 * 3600
This is an old question, but many of the answers posted above appear to be incorrect.
I came up with my own solution:
function getStartAndEndDate($week, $year){
$dates[0] = date("Y-m-d", strtotime($year.'W'.str_pad($week, 2, 0, STR_PAD_LEFT)));
$dates[1] = date("Y-m-d", strtotime($year.'W'.str_pad($week, 2, 0, STR_PAD_LEFT).' +6 days'));
return $dates;
}
First we need a day from that week so by knowing the week number and knowing that a week has seven days we are going to do so the
$pickADay = ($weekNo-1) * 7 + 3;
this way pickAday will be a day in our desired week.
Now because we know the year we can check which day is that.
things are simple if we only need dates newer than unix timestamp
We will get the unix timestamp for the first day of the year and add to that 24*3600*$pickADay and all is simple from here because we have it's timestamp we can know what day of the week it is and calculate the head and tail of that week accordingly.
If we want to find out the same thing of let's say 12th week of 1848 we must use another approach as we can not get the timestamp. Knowing that each year a day advances 1 weekday meaning (1st of november last year was on a sunday, this year is on a monday, exception for the leap years when it advances 2 days I believe, you can check that ). What I would do if the year is older than 1970 than make a difference between it and the needed year to know how many years are there, calculate the day of the week as my pickADay was part of 1970, shift it back one weekday for each. $shiftTimes = ($yearDifference + $numberOfLeapYears)%7, in the difference. shift the day backwords $shiftTimes, then you will know what day of the week was that day those years ago, then find the weekhead and weektail. Same thing can be used also for the future if it seems simpler. Try it if it works and tell me if it does not.
For documentation (since Google ranks this question first when searching for "php datetime start end this week").
If you need the startdate and enddate for the current week (using DateTime):
$dateTime = new DateTime('now');
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dateTime->modify('Sunday this week');
var_dump($monday->format('Y-m-d')); // e.g. 2018-06-25
var_dump($sunday->format('Y-m-d')); // e.g. 2018-07-01
Hope this will help.
The "first day of the week" is subjective. Some cultures use "Monday" others "Sunday", maybe others something else?
For my purposes, I want the first day of the week to be "Sunday" and the last day of the week to be "Saturday".
Also, using DateTime with no arguments will default to "now" which includes the current time. The following method will disregard the current time by specifying "today" in the DateTime constructor.
Furthermore the string "sunday this week" does not seem to be reliable. It actually will return Sunday the next week (according to my view of what a week is).
I've built a method which returns a PHP object containing two DateTime objects. One for the first day (Sunday) of the given week, the second for the last day (Saturday) of the given week.
function get_first_and_last_day_of_week( $year_number, $week_number ) {
// we need to specify 'today' otherwise datetime constructor uses 'now' which includes current time
$today = new DateTime( 'today' );
return (object) [
'first_day' => clone $today->setISODate( $year_number, $week_number, 0 ),
'last_day' => clone $today->setISODate( $year_number, $week_number, 6 )
];
}
Have you tried PHP relative dates? It might work.
Even if you dont want to use a specific date you cannot escape it. You can calculate a week based on the date ONLY.
Steps:
get the first day of the year
decide when the first week starts ( there are some rules that include first Thursday if I remember.
add some number of weeks (your first param). Zend_Date has an add() function where you can add weeks for example. This will give you the first day of the week.
offset and get the last day.
I would recommend working with a consistent dates sistem like Zend_Date or Pear Date.
function getStartAndEndDate($week, $year)
{
$week_start = new DateTime();
$week_start->setISODate($year,$week);
$return[0] = $week_start->format('d-M-Y');
$time = strtotime($return[0], time());
$time += 6*24*3600;
$return[1] = date('d-M-Y', $time);
return $return;
}
$dateParam = '2018-06-10';
$week = date('w', strtotime($dateParam));
$date = new DateTime($dateParam);
$firstWeek = $date->modify("-".$week." day")->format("Y-m-d H:i:s");
$endWeek = $date->modify("+6 day")->format("Y-m-d H:i:s");
echo $firstWeek."<br/>";
echo $endWeek;
will print
2018-06-10 00:00:00
2018-06-16 00:00:00
hopefully will help

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