I was using the following code for some months now without any issue in order to get the current week start/end date (Monday/Sunday):
date_default_timezone_set('Europe/Bucharest'); //this is the default in php.ini
$monday = strtotime('next Monday -1 week');
$monday = date('w', $monday)==date('w') ? $monday+7*86400 : $monday;
$sunday = strtotime(date("Y-m-d",$monday)." +6 days");
echo "Current week start/end date:<br>";
echo $this_week_sd = date("Y-m-d",$monday)."<br>";
echo $this_week_ed = date("Y-m-d",$sunday)."<br>";
//Expected result:
2018-10-29
2018-11-04
However, as of Today this for some reason has been offset by 1 day:
//Actual incorrect result:
2018-10-28
2018-11-03
Then I remembered that Yesterday the clock went back 1 hour due to DST, so I decided to change the timezone from Europe/Bucharest to Europe/Istanbul which still has a +3 hours advance against GMT:
date_default_timezone_set('Europe/Istanbul');
//Now the result is correct:
2018-10-29
2018-11-04
Question is, how can I offset DST in the current code so that I could keep the relative week dates in accordance with Europe/Bucharest timezone? Any pointers or explanations would be appreciated. Thank you.
If you just want to fix your current Code, just replace your three "ugly" ;-) lines:
$monday = strtotime('next Monday -1 week');
$monday = date('w', $monday)==date('w') ? strtotime(date("Y-m-d",$monday)." +7 days") : $monday;
$sunday = strtotime(date("Y-m-d",$monday)." +6 days");
with those "nice" one, and it will work.
$monday = strtotime('monday this week');
$sunday = strtotime('sunday this week');
PHPs relative Date Expressions can handle this nice.
I would do this using the DateTime class and keep everything in UTC so you never have to worry about daylight savings time:
$today = new DateTime('now', new DateTimeZone('UTC'));
$day_of_week = $today->format('w');
$today->modify('- ' . (($day_of_week - 1 + 7) % 7) . 'days');
$sunday = clone $today;
$sunday->modify('+ 6 days');
echo $today->format('Y-m-d') . "\n";
echo $sunday->format('Y-m-d');
Output:
2018-10-29
2018-11-04
Demo on 3v4l.org
I am aware that there is more than one way to skin a cat, but in this case I was interested in how to fix my current code and more importantly to find out what's wrong with it.
Thank you all for your suggestions, especially to #misorude for pointing out the obvious flaw in my initial code, whereas "not every day has 86400 seconds", which is especially true during DST.
So here's the updated working code using relative "days" instead of fixed seconds amount:
$monday = strtotime('next Monday -1 week');
$monday = date('w', $monday)==date('w') ? strtotime(date("Y-m-d",$monday)." +7 days") : $monday;
$sunday = strtotime(date("Y-m-d",$monday)." +6 days");
echo "This week start/end date:<br>";
echo $this_week_sd = date("Y-m-d",$monday)."<br>";
echo $this_week_ed = date("Y-m-d",$sunday)."<br>";
//output:
This week start/end date:
2018-10-29
2018-11-04
Once again, thank you all for your inputs. Much appreciated!
Related
It's monday and I run the following:
$d = date('d-m-Y', strtotime('this tuesday'));
Which gives me date the of tomorrow, 08-07-2014
If i run
$d = date('d-m-Y', strtotime('next tuesday'));
It provides me the same.
But how can i easiest get the next tuesday in the next week (not tomorrow)?
Just try with:
strtotime('this tuesday +1 week')
You can do the following
$d = date('d-m-Y', strtotime('next week tuesday'));
You can add days also to get desire result like :
date('Y-m-d', strtotime('this tuesday +7 days'));
Here's a summary of the issue: On Sundays, strtotime('this week') returns the start of next week.
In PHP, the week seems to start on Monday. But, on any day except Sunday, this code
echo date('Y-m-d', strtotime('monday this week', strtotime('last sunday')));
Outputs the date of this week's Monday, when it seems like it should be outputting last weeks Monday. It seems like, in this case, PHP is treating both Sunday and Monday as the the start of the week. It's now Monday, Dec 10, 2012, or 2012-12-10. date('Y-m-d', strtotime('sunday last week')) returns 2012-12-09 - yesterday.
Is this a bug, or am I missing something? It seems like a bug this obvious should be fairly well known, but I can't find anything about it. Is the only way to get the start of the week to use some special handling for Sundays?
$week_offset = (int) 'sunday' == date('l');
$week_start = strtotime("-$week_offset monday"); // 1 or 0 Mondays ago
As far as I can tell, this is a bug. I see no logical reason why strtotime('this week'); should return a future date. This is a pretty major bug. In my particular case, I had a leaderboard that showed the users with the most points since the beginning of the week. But on Sundays, it was empty because strtotime returned a timestamp for a future date. I was doubtful, because just I don't know how this could have gone unnoticed, but I couldn't find any other reports of this bug.
Thanks for all your time and help, folks.
This answer is late, but it's something that I've been struggling with. Every solution I've tried so far has malfunctioned for one reason or another. This is what I ended up with that worked for me. (though it may be look pretty, it at least works).
$thisMonday = strtotime('next Monday -1 week', strtotime('this sunday'));
Here is how you can get Monday of current week:
echo date("Y-m-d", strtotime(date('o-\\WW')));
It's not ideal but this is what I resorted to using:
if(date('N') == 7) {
$date = date('Y-m-d',strtotime('monday last week'));
} else {
$date = date('Y-m-d',strtotime('monday this week'));
}
I think the only problem with your coding is TimeZone.
Solution:
Set your own time Zone. Here is the example of my own time zone:
Example
date_default_timezone_set('Asia/Kolkata');
Set the above line before calling any time function.
Have a nice day.
I think instead of trying
echo date('Y-m-d', strtotime('monday this week', strtotime('last sunday')));
you should try
echo date('Y-m-d', strtotime('monday last week'));
Try this code
// set current date
$date = date("m/d/Y");
$ts = strtotime($date); // also $ts = time();
// find the year and the current week
$year = date('o', $ts);
$week = date('W', $ts);
// print week for the current date
$i = 1; // 1 denotes the first day of week
$ts = strtotime($year.'W'.$week.$i);
echo $day = date("l", $ts); // generate the name of day
echo "<br>";
echo $day = date("Y-m-d", $ts); // generate the date
You will get the the date of current week, whether you are on monday you will get the date of that monday.
If you want the most recent monday:
function mostRecentMonday(){
if(date("w") == 1){
return strtotime("midnight today");
} else {
return strtotime("last monday");
}
}
Easy to modify to use DateTime, or, to even specify a different date to use as the base.
Based on Bryant answer :
$first_week_date = date('d F Y', strtotime('next Monday -1 week', strtotime('this sunday')));
$last_week_date = date('d F Y', strtotime('next Monday -1 week + 6 days', strtotime('this sunday')));
This is for thos looking for a friendly solution that works with any day.
function getWeekStart($week_start_day = "Monday") {
$week_days = array("Sunday"=>0,"Monday"=>1,"Tuesday"=>2,"Wednesday"=>3,"Thursday"=>4,"Friday"=>5,"Saturday"=>6,);
if(!isset($week_days[$week_start_day])) {
return false;
} else {
$start_day = $week_days[$week_start_day];
$today = date("w");
$one_day = (60 * 60 * 24);
if($today < $start_day) {
$days_difference = 7 - ($start_day - $today);
} else {
$days_difference = ($today - $start_day);
}
$week_starts = strtotime(date("Y-m-d 00:00:00")) - ($one_day * $days_difference);
return $week_starts;
}
}
//Test: If today is Monday, it will return today's date
echo date("Y-m-d H:i:s", getWeekStart("Monday"));
I expected this functional to return 6/30/2005 instead of 7/1/2005.
print date("m/d/Y", strtotime("12/31/2004 +6 month"));
Similarly, print date("m/d/Y", strtotime("1/31/2011 +1 month")) returns 03/03/2011 while would like it to return 2/28/2011.
Does anyone know if there is a straight forward way to show the last day of the added month?
How about this?
echo date("m/d/Y", strtotime("last day of 12/31/2004 + 6 month")); // 6/30/2005
echo date("m/d/Y", strtotime("last day of 1/31/2011 + 1 month")); // 2/28/2011
Demo
Edit: For your reference, here is a link to the documentation for relative times.
as strtotime continue in to next month if there isn't enoghe days that month,
you can back 6 month and check if its end up on the start date
$date2 = date("Y-m-d", strtotime("{$date} +6 months"));
$date3 = date("Y-m-d", strtotime("{$date2} -6 months"));
if($date3 != $date)
{
$date2 = date("Y-m-t", strtotime("{$date2} -1 months"));
}
(or in your case "m/t/Y")
One simple way is to actually go one month ahead of the day you want and then make the day value zero. Also, mktime() might be easier
$mymonth = 2; // I want the last day of February
echo date('m/d/Y', mktime(0,0,0,$mymonth+1,0,2011));
This should return 2/28/2011.
strtotime does the best it can with conflicting information. Saying
1/31/2011 +1month
would mean advancing to
2/31/2011
but February only has 28 (sometimes 29) days. 2011 isn't a leap year, so the "31st of February" gets normalized to "March 3rd".
The same applies for '12/31/2004 +6month'. That takes you to June 31st, 2005. But June only has 30 days, so the date is normalized to July 1st instead.
i am making some statistics, i want to select the time from (last week only) and this week.
for this week its easy:
$start = strtotime('this week');
$finish = time();
for last week
$start = strtotime('last week');
$finish = ??????
This?
$start = strtotime('2 weeks ago');
$finish = strtotime('last week');
Edit: change credit to #Dominic Barnes's comment.
If the question is for statistical PHP script. Then all of the answers and basically the question is wrong.
Last week in statistics = One before currently running week from Sunday to Monday
This week in statistics = Currently running week from Sunday to Monday
(or Monday to Sunday, depending on which calendar you are used to, but in PHP that's one week)
This means, its not from today minus 7 days. That is not last or this week. So the selected answer currently, is in correct and counts 7 days back. Granted, its Sunday, at the time of testing, so it shows correct. But by editing the now date, you can see the problem:
// Selected answer:
$start = strtotime('2 weeks ago');
$finish = strtotime('last week');
// But if today isn't Sunday, you can see the code is wrong:
echo date("d.m.Y", strtotime("1 week ago", strtotime('yesterday')));
// Output: 15.08.2015 00:00:00 - 17.08.2015 00:00:00
You have to set the start of the week and the end of the week. strtotime() can support more stuff, so you can most likely make this answer better and more neat. However you get the working code and a good example of the logic from...
My proposed solution:
$today = strtotime('today 00:00:00');
$this_week_start = strtotime('-1 week monday 00:00:00');
$this_week_end = strtotime('sunday 23:59:59');
$last_week_start = strtotime('-2 week monday 00:00:00');
$last_week_end = strtotime('-1 week sunday 23:59:59');
echo date('d.m.Y H:i:s', $today) . ' - Today for example purposes<br />';
echo date('d.m.Y H:i:s', $this_week_start) . ' - ' . date('d.m.Y H:i:s', $this_week_end) . ' - Currently running week period<br />';
echo date('d.m.Y H:i:s', $last_week_start) . ' - ' . date('d.m.Y H:i:s', $last_week_end) . ' - Last week period<br />';
Above currently produces:
30.08.2015 00:00:00 - Today for example purposes
24.08.2015 00:00:00 - 30.08.2015 23:59:59 - Currently running week period
17.08.2015 00:00:00 - 23.08.2015 23:59:59 - Last week period
Because for statistics, it has to be accurate and if the end would be 00:00:00, then that date wont be counted in. And if the date would be one day later at 00:00:00, then the date is not correct. There for, this solution is the correct way to do this, for statistical purposes at least.
Is that what you want?
$start = strtotime('last week');
$finish = strtotime('this week');
Dominic also points out that time() === strtotime('this week') (CodePad).
If searching for the last week for statistical purposes, starting on Monday, ending on Sunday:
$last_week_start = strtotime("monday last week");
$last_week_end = strtotime("monday this week - 1 second");
"this week" is important, otherwise, if this weeks monday is already in the past (e.g. if it is tuesday already), it will give you the monday of next' week.
As for the months/years, I used the classy mktime approach:
last month
$last_month_start = mktime(0, 0, 0, date('m')-1, 01);
$last_month_end = mktime(23, 59, 59, date('m'), 0);
last year
$last_year_start = mktime(0, 0, 0, 1, 1, date('Y')-1);
$last_year_end = mktime(23, 59, 59, 1, 0, date('Y'));
If you are looking for "Last Week" instead of Last 7 days
$start = strtotime('Last Week'); // Will give you last Monday
$finish = strtotime('Last Sunday'); // Will give you last Sunday
I think its possible but i cant come up with the right algorithm for it.
What i wanted to do was:
If today is monday feb 2 2009, how would i know the date of last week's tuesday? Using that same code 2 days after, i would find the same date of last week's tuesday with the current date being wednesday, feb 4 2009.
Most of these answers are either too much, or technically incorrect because "last Tuesday" doesn't necessarily mean the Tuesday from last week, it just means the previous Tuesday, which could be within the same week of "now".
The correct answer is:
strtotime('tuesday last week')
I know there is an accepted answer already, but imho it does not meet the second requirement that was asked for. In the above case, strtotime would yield yesterday if used on a wednesday. So, just to be exact you would still need to check for this:
$tuesday = strtotime('last Tuesday');
// check if we need to go back in time one more week
$tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400 : $tuesday;
As davil pointed out in his comment, this was kind of a quick-shot of mine. The above calculation will be off by one once a year due to daylight saving time. The good-enough solution would be:
$tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400+7200 : $tuesday;
If you need the time to be 0:00h, you'll need some extra effort of course.
PHP actually makes this really easy:
echo strtotime('last Tuesday');
See the strtotime documentation.
Working solution:
$z = date("Y-m-d", strtotime("last Saturday"));
$z = (date('W', strtotime($z)) == date('W')) ? (strtotime($z)-7*86400+7200) : strtotime($z);
print date("Y-m-d", $z);
you forgot strtotime for second argument of date('W', $tuesday)
hmm.
convert $tuesday to timestamp before "$tuesday-7*86400+7200"
mde.
// test: find last date for each day of the week
foreach (array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') as $day) {
print $day . " => " . date('m/d/Y', last_dayofweek($day)) . "\n";
}
function last_dayofweek($day)
{
// return timestamp of last Monday...Friday
// will return today if today is the requested weekday
$day = strtolower(substr($day, 0, 3));
if (strtolower(date('D')) == $day)
return strtotime("today");
else
return strtotime("last {$day}");
}
<?php
$currentDay = date('D');
echo "Today-".$today = date("Y-m-d");
echo "Yesterday-".$yesterday = date("Y-m-d",strtotime('yesterday'));
echo "Same day last week-".$same_day_last_week = date("Y-m-d",strtotime('last '.$currentDay));
?>
Do not use manual calculation, use DateTime object instead. It has proper implementation, takes into account leap years, yeap seconds, etc.
$today = new \DateTime();
$today->modify('tuesday last week');
The modify method modifies the date relative to it's state, so if you set the date to a different date, it calculates it relative to it.
$date = new \DateTime('2020-01-01');
echo $date->format('Y-m-d'); // 2020-01-01
$date->modify('tuesday last week');
echo $date->format('Y-m-d'); // 2019-12-24