Week beginning and end PHP - php

Say I wanted to get the week beginning and ending, for example:
Mon 29th June - week start
Sun 5th July - week end
and then tomorrow (Mon 6th July) it will say:
Mon 6th July - week start
Sun 12th July - week end
Is this the right way to do it?
$week_start = date('Y-m-d', strtotime('last monday'));
$week_end = date('Y-m-d', strtotime('this sunday'));

DateTime class has this nice method called setIsoDate():
$start = new DateTime();
$start->setIsoDate($start->format('o'), $start->format('W'));
$end = clone $start;
$end->modify('+6 day');
echo "From: " . $start->format('Y-m-d') . " to: " . $end->format('Y-m-d');
demo

That would not work properly if the current date is Monday. last monday would then translate to the Monday the previous week.
I would use this syntax instead:
$week_start = date('Y-m-d', strtotime('last monday', strtotime('tomorrow')));
$week_end = date('Y-m-d', strtotime('this sunday'));
You might also consider avoiding those "advanced" relative formats, and seek the correct dates based on the current weekday. Might be a bit more reliable, as those week formats don't always seem to behave as one might expect, and the logic behind them isn't readily available.
This solution uses simpler strtotime formats, and instead puts the seek logic in the code itself. As such, it's a lot more predictable, if a little less elegant.
$weekday = date("N"); // 1 = Monday, 7 = Sunday
$week_start = date("Y-m-d", strtotime("-" . ($weekday - 1) . " days"));
$week_end = date("Y-m-d", strtotime("+" . (7 - $weekday) . " days"));
Note that the date("N") flag is only available in PHP 5.1 and later. For older version you'd need to use date("w"), and move the Sunday value to the back.
$weekday = date("w"); // 0 = Sunday, 6 = Saturday
if ($weekday == 0) {
$weekday = 7;
}

Related

PHP get ISO week number for a date whose starting day is other than Monday

According to the ISO standar, the 52nd week of 2013, when the week starts on Saturday, starts 2013-12-28 and ends 2014-01-03 (inclusive).
Code:
echo date('Y-m-d', strtotime("2013-W52-6"));//prints 2013-12-28
Now, I am trying to figure out the inverse using PHP. If I have the date 2014-01-03, how to know the ISO weeknumber of that date if the week starts on Saturday?
Use the DateTime class:
createFromFormat() to create the object based on the string you have
then format('W')
$date = "2013-12-28";
$dayofyear = date("z", $date);
$week = floor($dayofyear / 7) + 1;
// I assume week starts with Monday (I think as ISO does?)
// so only weeks that start on sunday will count as "week 0" instead of "week 1"
// I could be wildly wrong, adjust according to your needs
$first_day = date("w", date("Y", $date) . "-01-01");
if ($first_day == 6)
--$week;
echo $week;
$date = "2013-12-28";
$date_array = explode("-", $date);
$date = mktime(0, 0, 0, $date_array[1], $date_array[2], $date_array[0]);
$week_number = date('W', $date);
echo $week_number;
Something like this.

Calculate day of month with month, year, day of week and number of week

How can I calculate the day of month in PHP with giving month, year, day of week and number of week.
Like, if I have September 2013 and day of week is Friday and number of week is 2, I should get 6. (9/6/2013 is Friday on the 2nd week.)
One way to achieve this is using relative formats for strtotime().
Unfortunately, it's not as straightforward as:
strtotime('Friday of second week of September 2013');
In order for the weeks to work as you mentioned, you need to call strtotime() again with a relative timestamp.
$first_of_month_timestamp = strtotime('first day of September 2013');
$second_week_friday = strtotime('+1 week, Friday', $first_of_month_timestamp);
echo date('Y-m-d', $second_week_friday); // 2013-09-13
Note: Since the first day of the month starts on week one, I've decremented the week accordingly.
I was going to suggest to just use strtotime() in this fashion:
$ts = strtotime('2nd friday of september 2013');
echo date('Y-m-d', $ts), PHP_EOL;
// outputs: 2013-09-13
It seems that this is not how you want the calendar to behave? But it is following a (proper) standard :)
This way its a little longer and obvious but it works.
/* INPUT */
$month = "September";
$year = "2013";
$dayWeek= "Friday";
$week = 2;
$start = strtotime("{$year}/{$month}/1"); //get first day of that month
$result = false;
while(true) { //loop all days of month to find expected day
if(date("w", $start) == $week && date("l", $start) == $dayWeek) {
$result = date("d", $start);
break;
}
$start += 60 * 60 * 24;
}
var_dump($result); // string(2) "06"

PHP: Week starts on Monday, but "monday this week" on a Sunday gets Monday next week

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"));

last week, this week (php)

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

Repeating Events on the "nth" Weekday of Every Month

I've looked at at least 2 dozen topics about this and haven't really found a good answer yet, so I come to you to ask once again for answers regarding the dreaded topic of Repeating Events.
I've got Daily, Weekly, Monthly, and Yearly repeats working out fine for now (I still need to revamp the system with Exception events and whatnot, but it works for the time being). But, we want to be able to add the ability to repeat events on the (1st,2nd,3rd,4th,5th) [Sun|Mon|Tue|Wed|Thu|Fri|Sat] of every month, every other month, and every three months.
Now, if I can just understand the logic for the every month, I can figure out the every other month and the every three months.
Here's a bit of what I have so far (note: I'm not saying I have the best way of doing it or anything, but the system is one we update very slowly over time when we aren't busy with other projects, so I make the code more efficient as I have the time).
First I get the starting and ending dates formatted for date calculations:
$ending = $_POST['end_month'] . "/" . $_POST['end_day'] . "/" . substr($_POST['end_year'], 2, 2);
$starting = $_POST['month'] . "/" . $_POST['day'] . "/" . substr($_POST['year'], 2, 2);
Then I get the difference between those two to know how many times to repeat using a function I'm fairly certain I found on here some time ago and dividing that amount by 28 days to get just about how many TIMES it needs to repeat so that there is one a month:
$repeat_number = date_diff($starting, $ending) / 28;
//find the difference in DAYS between the two dates
function date_diff($old_date, $new_date) {
$offset = strtotime($new_date) - strtotime($old_date);
return $offset/60/60/24;
}
Then I add the (1st,2nd,etc...) part to the [Sun|Mon|etc...] part to figure out what they are looking for giving me somehthing like 'first Sunday' :
$find = $_POST['custom_number']. ' ' . $_POST['custom_day'];
Then I use a loop that runs the number of times this needs to repeat (the $repeat_number from above):
for($m = 0; $m <= $repeat_number; $m++) {
if($m == 0) {
$month = date('F', substr($starting,0,2));
} else {
$month = date('F', strtotime($month . ' + ' . $m . ' months'));
}
$repeat_date = strtotime($find . ' in ' . $month);
}
Now, I'm aware this code doesn't work, I at one time did have code that turned up the correct month and year for the repeat, but wouldn't necessarily find the first tuesday or whatever it was that was being looked for.
If anyone could point me back in the right direction, it would be most appreciated. I've been lurking in the community for some time now, just started trying to actively participate recently.
Thanks in advance for any input or advice you can provide.
Here's a possible alternative for you. strtotime is powerful, and the syntax includes really useful bits like comprehensive relative time and date wording.
You can use it to generate the first through Nth specific weekdays of a specific month by using the format " of ". Here's an example using date_create to invoke a DateTime object, but regular old strtotime works the same way:
php > $d = date_create('Last Friday of March 2011'); if($d instanceof DateTime) echo $d->format('l F d Y H:i:s');
Friday March 25 2011 00:00:00
php > $d = date_create('First Friday of March 2011'); if($d instanceof DateTime) echo $d->format('l F d Y H:i:s');
Friday March 04 2011 00:00:00
php > $d = date_create('First Sunday of March 2011'); if($d instanceof DateTime) echo $d->format('l F d Y H:i:s');
Sunday March 06 2011 00:00:00
php > $d = date_create('Fourth Sunday of March 2011'); if($d instanceof DateTime) echo $d->format('l F d Y H:i:s');
Sunday March 27 2011 00:00:00
php > $d = date_create('Last Sunday of March 2011'); if($d instanceof DateTime) echo $d->format('l F d Y H:i:s');
Sunday March 27 2011 00:00:00
It will also overflow the month, if you ask for an invalid one:
php > $d = date_create('Ninth Sunday of March 2011'); if($d instanceof DateTime) echo $d->format('l F d Y H:i:s');
Sunday May 01 2011 00:00:00
Note that it only works with the ordinal number wording. You can't pass "1st" or "3rd", unfortunately.
Once you use this to grab the proper Nth weekday, you can then simply add the number of needed weekdays to skip (7 for one week, 14 for two, 21 for three, etc) as required until the designated end date or designated number of weeks has passed. Once again, strtotime to the rescue, using the second argument to chain together relativeness:
php > echo date('l F d Y H:i:s', strtotime('+14 days', strtotime('First Thursday of March 2011')));
Thursday March 17 2011 00:00:00
(My local copy also accepted '+14 days First Thursday of March 2011', but that felt kind of weird.)
I have a more simple method, although it may seem hack-ish.
What we can do is take the start date, and infer it's "n" value from it by taking the ceiling of its day divided by 7.
For example, if your start date is the 18th, we divide by 7 and take the ceiling to infer that it is the 3rd "whatever-day" of the month.
From there we can simply repeatedly add 7 days to this to get a new date, and whenever the new date's ceilinged 7-quotient is 3, we've hit the next "nth whatever-day" of the month.
Some code can be seen below:
$day_nth = ceil(date("j", strtotime($date))/7);
for ($i = 0; $i < $number_of_repeats; $i++) {
while (ceil(date("j", strtotime($date))/7) != $day_nth)
$date = date("Y-m-d", strtotime("+7 days", strtotime($date)));
/* Add your event, or whatever */
/* Now we increment date by 7 days before the loop starts again,
** otherwise the while loop would never execute and we'd just be
** adding to the same date repeatedly. */
$date = date("Y-m-d", strtotime("+7 days", strtotime($date)));
}
What's nice about this method is that we don't even have to concern ourselves with which day of the week we're dealing with. We just infer everything from the start date and away we go.
I make it like that:
//$typeOfDate = 0;
$typeOfDate = 1;
$day = strtotime("2013-02-01");
$to = strtotime(date("Y-m-d", $day) . " +6 month");
if ($typeOfDate == 0) { //use the same day (number) of the month
$dateArray[] = date("Y-m-d", $day);
$event_day_number = date("d", $day);
while ($day <= $to) {
$nextMonth = date("m", get_x_months_to_the_future($day));
$day = strtotime(date("Y-" . $nextMonth . "-d", $day));
$dateArray[] = date("Y-m-d", $day);
}
}
if ($typeOfDate == 0) { //use the same day (like friday) of the month
$dateArray[] = date("Y-m-d", $day);
$monthEvent = date("m", $day);
$day = strtotime(date("Y-m-d", $day) . " +4 weeks");
$newMonthEvent = date("m", $day);
if ($monthEvent == $newMonthEvent) {
$day = strtotime(date("Y-m-d", $day) . " +7 days");
}
while ($day <= $to) {
$dateArray[] = date("Y-m-d", $day);
$monthEvent = date("m", $day);
$day = strtotime(date("Y-m-d", $day) . " +4 weeks");
$newMonthEvent = date("m", $day);
if ($monthEvent == $newMonthEvent) {
$day = strtotime(date("Y-m-d", $day) . " +7 days");
}
}
}

Categories