I can add any number of months to a date:
strtotime("+ 1 months", '2017-01-31') // result: 2017-03-03
But I want to do this without going to the next month.
in this case I want the result 2017-02-28, that is, the last day of the month before the target month.
There seems to be a lot of overcomplicating in these answers. You want the last day of the month before your target month, which is also always going to be 1 day before the first day of the target month. This can be expressed quite simply:
$months = 1;
$relativeto = '2017-01-31';
echo date(
'Y-m-d',
strtotime(
'-1 day',
strtotime(
date(
'Y-m-01',
strtotime("+ $months months", strtotime($relativeto))
)
)
)
);
Try using the DateTime object like so:
$dateTime = new \DateTime('2017-01-31');
$dateTime->add(new \DateInterval('P1M'));
$result = $dateTime->format('Y-m-d');
Use PHP's DateTime to accomplish this, specifically the modify() method.
$date = new DateTime('2006-12-12');
$date->modify('+1 month');
echo $date->format('Y-m-d');
If the idea here is not to allow the date to overflow into the next month, which PHP does, then you'll have to impose that constraint in your logic.
One approach is to check the modified month against the given month before returning the updated date.
function nextMonth(DateTimeImmutable $date) {
$nextMonth = $date->add(new DateInterval("P1M"));
$diff = $nextMonth->diff($date);
if ($diff->d > 0) {
$nextMonth = $nextMonth->sub(new DateInterval("P{$diff->d}D"));
}
return $nextMonth;
}
$date = new DateTimeImmutable("2017-01-31");
$nextMonth = nextMonth($date);
echo "{$date->format('Y-m-d')} - {$nextMonth->format('Y-m-d')}\n";
//2017-01-31 - 2017-02-28
$date = new DateTimeImmutable("2017-10-31");
$nextMonth = nextMonth($date);
echo "{$date->format('Y-m-d')} - {$nextMonth->format('Y-m-d')}\n";
//2017-10-31 - 2017-11-30
The nextMonth() function in the example above, imposes the constraint of not overflowing into the next month. Note that what PHP actually does is try to find the corresponding day, in the following consecutive number of months added, not just add a given number of months to the existing date. I simply undo this last part by subtracting any additional days beyond the 1 month interval in the function above.
So for example, strtotime("+1 month") for the date "2017-01-31", tells PHP find the 31st day that is +1 month from "2017-01-31". But of course, there are only 28 days in February, so PHP goes into March and counts up 3 more days to compensate.
In other words, it's not just add +1 month to this date, but add +1 month to this date and arrive at the same day of the month as is in the given date. Which is where the overflow happens.
Update
Since you've now made it clear that you actually want the last day of the month (not necessarily the same day of the next month without the overflow provision) you should instead just explicitly set the day of the month.
function nextMonth(DateTimeImmutable $date) {
$nextMonth = $date->setDate($date->format('Y'), $date->format('n') + 1, 1);
$nextMonth = $date->setDate($nextMonth->format('Y'), $nextMonth->format('n'), $nextMonth->format('t'));
return $nextMonth;
}
$date = new DateTimeImmutable("2017-02-28");
$nextMonth = nextMonth($date);
echo "{$date->format('Y-m-d')} - {$nextMonth->format('Y-m-d')}\n";
// 2017-02-28 - 2017-03-31
is there a way in PHP to get the next date(s) using a 4-week interval from a given date ?
Example:
My start date is Friday, Jan 03, 2014 and my interval is every 4 weeks from that date.
What I am looking for is the next date (or dates, if possible) from the current date that matches this 4-week interval.
In the above example this would be Friday, May 23, 2014 (then June 20, 2014, July 18, 2014 etc.).
I know I can get the current date as follows: $today = date('Y-m-d');
and I could probably set the start date like this: $start = date('2014-01-03');
but I don't know how to calculate the interval and how to find out the next matching date(s).
You should read up on the DateTime classes, specifically DatePeriod and DateInterval:
$start = new DateTime('2014-01-03');
$interval = DateInterval::createFromDateString('4 weeks');
$end = new DateTime('2015-12-31');
$occurrences = new DatePeriod($start, $interval, $end);
foreach ($occurrences as $occurrence) {
echo $occurrence->format('Y-m-d') . PHP_EOL;
}
DatePeriod takes a start date and a DateInterval and allows you traverse over the object to get all dates within the boundaries using the given interval. The cut off can be either a set number of cycles (so the next 10 dates) or an end date (like above), even if the end date is not one of the dates the interval falls on (it will stop below it). Or you can use an 8601 interval notation string (which sounds so much fun, huh?), but I'm pretty shaky on that.
If 4-week interval means 7 x 4 = 28 days, you can obtain the "next date" by:
$today = new DateTime();
$next_date = $today->add(new DateInterval('P28D'));
$next_next_date = $next_date->add(new DateInterval('P28D'));
$next_next_next_date = $next_next_date->add(new DateInterval('P28D'));
And if you want to calculate more "next dates", you can repeat the add() to repetitively add 28 days to your date.
Note: Beside using P28D, you can use P4W, which means 4 weeks.
While some answers may suggest using strtotime(), I find the object-oriented approach more structured. However, DateInterval is only available after PHP >= 5.3.0 (while DateTime is available after PHP >= 5.2.0)
You could use strtotime()
echo date('Y-m-d', strtotime('now +4 weeks'));
UPDATED:
$start = date('Y-m-d', strtotime('2014-01-03 +4 weeks'));
echo $start;
You could also run this in a for loop to get the next 6 or more dates. For example:
$Date = "2014-01-03";
$Int = 6;
for($i=0; $i<$Int; $i++){
$Date = date('Y-m-d', strtotime('{$Date} +4 weeks'));
echo $Date;
}
A client wants a newsletter to be automatically generated every Monday, showing the schedule for the upcoming week. That's easy:
if(date('N', $time)==1) { /* Stuff */ }
Attach that to a crontab running nightly and I'm good to go.
However, if the newsletter is being generated in the last week of the month, it needs to show the schedule for the upcoming month. How would I determine when the monthly schedule needs to be generated?
date('m') == date('m', strtotime('+1 week'))
If the month a week from the date the report is running is different than the current month, show the report!
if(date('n', $time) !== date('n', $time+518400)){
// Six days from now it will be a new month
}
One way might be to see if next Monday is in a different month.
if (date('n', $time) != date('n', $time + 7*24*60*60)) { ... }
You could be fancier, but this seems consistent with your existing code.
You can use the t date format param to see how many days are in the particular month. Try
if ((date('t', $time) - date('j', $time)) > 6) {
// in the last week of the month
}
I know this a answered but this will help more:
PHP's built-in time functions make this even simple. http://php.net/manual/en/function.strtotime.php
// Get first Friday of next month.
$timestamp = strtotime('first fri of next month');
// Get second to last Friday of the current month.
$timestamp = strtotime('last fri of this month -7 days');
// Format a timestamp as a human-meaningful string.
$formattedDate = date('F j, Y', strtotime('first wed of last month'));
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
Am trying to calculate the first day of last 3 weeks and first day of last 3 months in unix timestamp in PHP.
I know I have to use date function but am a bit lost. I do not have PHP 5.3 thus I cannot use relative formats.
Am using the above to decide whether or not to delete a backup. e.g.
if ($time > time()-3600*24*7 && $time < time()) {
echo "Keeping: $file<br/>";
}
I want to keep backups for:
Last 7 days
First day of last 3 weeks
First day of last 3 months
Am trying to calculate the first day of last 3 weeks and first day of last 3 months in unix timestamp in PHP.
I know I have to use date function but am a bit lost. I do not have PHP 5.3 thus I cannot use relative formats.
Am using the above to decide whether or not to delete a backup. e.g.
if ($time > time()-3600*24*7 && $time < time()) {
echo "Keeping: $file<br/>";
}
I want to keep backups for:
Last 7 days
First day of last 3 weeks
First day of last 3 months
Update
Adding the solution, as I figured it out with the help of Pekka
$a = (strtotime("last Monday-1 week"));
$b = (strtotime("last Monday-2 week"));
$c = (strtotime("last Monday-3 week"));
$d = (strtotime(date('m').'/01/'.date('Y').' 00:00:00'));
$e = (strtotime('-1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00')));
$f = (strtotime('-2 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00')));
I know this question quite old, but thought of sharing my own answer so that other people might find it useful. This worked in PHP 7.2 and not sure about other versions. To get first day of 3 months back, here is the code.
echo date('Y-m-d', strtotime("FIRST DAY OF -3 MONTH"));
result:
2021-01-01
Use strtotime()'s magic.
echo strtotime("-7 days");
echo strtotime("-3 weeks");
echo strtotime("-3 months");
strtotime() can even do stuff like last tuesday, midnight.....
To calculate dates you can use strtotime:
$last7days = strtotime('-7 days');
$last3weeks = strtotime('-3 weeks');
$last3months = strtotime('-3 months');
then simply compare it to $time value:
if ( $time > $last7days ) {
...
}