Get a date range covering 2 business weeks starting with current monday - php

I am having trouble adjusting a week range in PHP.
I have it working to show the current work week starting on monday.
So for this week it shows 11/29/2010 - 12/03/2010.
I need to modify this to start from the current work week's monday and show and end date of two fridays from the monday.
So for example currently it would show a start date of 11/29/2010 and and end date of 12/10/2010.
Here is my code
<?
$timestamp = time();
echo date("m/d/Y", strtotime("this monday", $timestamp));
echo " - ";
echo date("m/d/Y", strtotime("Next Friday", $timestamp));
?>
How do I add +7 to "Next Friday"
thx

You cannot use this monday to construct date time,
as it went pass Monday, it return next Monday
here is my suggestion
<?
$current_wkday = date('N', time());
switch ($current_wkday)
{
/* assuming on sunday, get next monday */
case 0: $this_monday = strtotime('+1 day'); break;
case 1: $this_monday = time(); break;
default: $this_monday = strtotime('-'.($current_wkday-1).'day'); break;
}
echo date("m/d/Y", $this_monday); /* 11days = 7+(5-1) */
echo " - ";
echo date("m/d/Y", $this_monday+(86400*11));
?>

Instead of strtotime("Next Friday", $timestamp) do strtotime("Next Friday", $timestamp) + 60*60*24*7 (add the number of seconds in a week).

Just realised that "previous monday" only works the current day is tuesday or later...but it's a starting point for you..
<?php
$monday = date('m/d/Y', strtotime("previous monday"));
$friday = date('m/d/Y', strtotime($monday . " + 11 days"));
echo $monday . ' - ' . $friday ;
?>

Related

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

1st I converted date to week number ( 01 to 53 ) in PHP and now i don't know how to get week number to first_date of week

Here a simple code of
date to week_number of year and now. How can I get start_date and end_date of week_number
$date_string = "2012-12-30";
echo "Weeknummer: " . date("W", strtotime($date_string));
There is many ways to do it, here is one.
I use "N" of date to determine what day the selected day is and use strtotimes way of understanding simple text to find previous or next Monday/Sunday.
$date_string = "2018-01-27";
$w =date("W", strtotime($date_string));
$N =date("N", strtotime($date_string));
If($N == 1){ // if monday
$monday = $date_string;
$sunday = date("Y-m-d", strtotime("next Sunday $date_string"));
}Elseif($N ==7){ // if sunday
$monday = date("Y-m-d", strtotime("previous Monday $date_string"));
$sunday = $date_string;
}Else{// any other weekday
$monday = date("Y-m-d", strtotime("previous Monday $date_string"));
$sunday = date("Y-m-d", strtotime("next Sunday $date_string"));
}
echo "Weeknummer: $w.\nMonday: $monday.\nSunday: $sunday.";
Output:
Weeknummer: 52.
Monday: 2012-12-24.
Sunday: 2012-12-30.
https://3v4l.org/UDoqF
You can use this:
<?php
$date_string = "2012-12-30";
$weekNumber = date("W", strtotime($date_string));
echo "Weeknummer: ".$weekNumber;
echo '</br>';
// get the year
$year = date("Y", strtotime($date_string));
// set the date string for the week number
$dateWeek = $year.'-W'.$weekNumber;
// increase the weekNumber to the next
$weekNumber = intval($weekNumber);
$weekNumber += 1;
// if it is lower than 10 add preceeding 0
if($weekNumber < 10) $weekNumber = '0'.$weekNumber;
// set the date string for the next week number
$dateWeekNext = $year.'-W'.$weekNumber;
echo '</br>';
// get the first day of the week
echo date('Y-m-d', strtotime($dateWeek));
echo '</br>';
// get the day before the first day of the next week
echo date('Y-m-d', strtotime($dateWeekNext . ' -1 day'));
?>
This outputs:
Weeknummer: 52
2012-12-24
2012-12-30

PHP Get 52 week start/end date for a specific year

I would like to calculate the start date from Tuesday and the end date to land on Mondays in the year 2016
I am trying to have the output
start date("j/n/Y"); end date("j/n/Y");
I have looked at similar SO questions, and google searches but its for specific week #'s, or not what I am trying to accomplish.
What I am trying to get is the following.
Start: 12/14/2015
End 12/21/2015
Start: 12/22/2015
End 12/28/2015
....
Start: 01/05/2016
End 01/11/2016
Start: 01/12/2016
End 01/18/2016
...
so on and soforth.
Any help would be greatly appreciated, and hope people dont downvote the crap out of this question. it is valid, and I have looked and cannot seem to find what I am after.
You can use the strtotime function to have the first tuesday of january 2016 and then loop 52 times, using next monday, and tomorrow. So you don't have to do any calculation.
<?php
$ts=strtotime("tuesday january 2016");
echo "<table>";
for ($i=0;$i<52;$i++) {
echo "<tr><td>Start: ".date("Y/m/d", $ts);
$ts=strtotime("next monday", $ts);
echo "</td><td>End: ".date("Y/m/d", $ts)."</td>\n";
echo "</td><td>Payweek: ".date("W", $ts)."</td></tr>\n";
$ts=strtotime("tomorrow", $ts);
}
echo "</table>";
You can try following code:
$start_date=date("m-d-Y", strtotime('tuesday this week'));
$end_date=date("m-d-Y", strtotime('monday next week'));
It will give you week starting from Tuesday and ending from Monday.
$oneWeek = 7*24*60*60; // 1 week in seconds
$curr_ts = time();
while ($curr_ts < strtotime('2017-01-01')) {
echo " Start: ",
date('m/d/Y', strtotime('tuesday this week', $curr_ts)),
"\nEnd ",
date('m/d/Y', strtotime('monday next week', $curr_ts)),
"\n";
$curr_ts = $curr_ts + $oneWeek;
}
While the date is less than your defined end date, loop over each week.
$date = Some start date ...;
$endDate = Some end date ...;
while (date_interval_format($date->diff($endDate),'%R') == '+') {
echo $date->format('j/n/Y') . " - " . $date->add(new DateInterval('P6D'))->format('j/n/Y') . "\n";
$date->add(new DateInterval('P1D'));
}

how can I get last week' date range in php?

how can I get last week' date range in php ?
see my codes bellow:
<?php
function get_last_week_dates(){
// how can i get the date range last week ?
// ex: today is 2014-2-8
// the week date range of last week should be '2014-1-26 ~ 2014-2-1'
}
?>
You can use strtotime()
$previous_week = strtotime("-1 week +1 day");
$start_week = strtotime("last sunday midnight",$previous_week);
$end_week = strtotime("next saturday",$start_week);
$start_week = date("Y-m-d",$start_week);
$end_week = date("Y-m-d",$end_week);
echo $start_week.' '.$end_week ;
UPDATE
Changed the code to handle sunday. If the current day is sunday then - 1 week will be previous sunday and again getting previous sunday for that will go the one week back.
$previous_week = strtotime("-1 week +1 day");
In addition if we need to find the current week and next week date
range we can do as
Current week -
$d = strtotime("today");
$start_week = strtotime("last sunday midnight",$d);
$end_week = strtotime("next saturday",$d);
$start = date("Y-m-d",$start_week);
$end = date("Y-m-d",$end_week);
Next Week -
$d = strtotime("+1 week -1 day");
$start_week = strtotime("last sunday midnight",$d);
$end_week = strtotime("next saturday",$d);
$start = date("Y-m-d",$start_week);
$end = date("Y-m-d",$end_week);
Simply use
date("m/d/Y", strtotime("last week monday"));
date("m/d/Y", strtotime("last week sunday"));
It will give the date of Last week's Monday and Sunday.
you need you use strtotime function for this
<center>
<?php
function get_last_week_dates()
{
// how can i get the date range last week ?
// ex: today is 2014-2-8
// the week date range of last week should be '2014-1-26 ~ 2014-2-1'
$startdate = "last monday";
if (date('N') !== '1')
{
// it's not Monday today
$startdate .= " last week";
}
echo "<br />";
$day = strtotime($startdate);
echo date('r', $day);
echo "<br />";
$sunday = strtotime('next monday', $day) - 1;
echo date('r', $sunday);
}
get_last_week_dates();
?>
</center>
Well just for the fun of trying to solve this:
date_default_timezone_set('UTC');
$firstDayOfLastWeek = mktime(0,0,0,date("m"),date("d")-date("w")-7);
$lastDayOfLastWeek = mktime(0,0,0,date("m"),date("d")-date("w")-1);
echo("Last week began on: ".date("d.m.Y",$firstDayOfLastWeek));
echo("<br>");
echo("Last week ended on: ".date("d.m.Y",$lastDayOfLastWeek));
This should do the trick
$startWeek = date('Y-m-d',strtotime("Sunday Last Week"));
$endWeek = date('Y-m-d',strtotime("Sunday This Week"));
this would not work if ran on a Monday. It would get last Sunday (the day before) to the next Sunday. So using Abhik Chakraborty's method with the above:
$startTime = strtotime("last sunday midnight",$previous_week);
$endTime = strtotime("next sunday midnight",$startTime);
$startDate = date('Y-m-d 00:00:00',$startTime);
$endDate = date('Y-m-d 23:59:59',$endTime);
This will now give
start = 2014-08-10 00:00:00
endDate = 2014-08-17 23:59:59
I know this is old but here's a much more succinct way of doing it:
$startDate = date("m/d/y", strtotime(date("w") ? "2 sundays ago" : "last sunday"));
$endDate = date("m/d/y", strtotime("last saturday"));
echo $startDate . " - " . $endDate
This one will produce the proper result and handles the Monday issue
<?php
$monday = strtotime("last monday");
$monday = date('W', $monday)==date('W') ? $monday-7*86400 : $monday;
$sunday = strtotime(date("Y-m-d",$monday)." +6 days");
$this_week_sd = date("Y-m-d",$monday);
$this_week_ed = date("Y-m-d",$sunday);
echo "Last week range from $this_week_sd to $this_week_ed ";
?>
Most of those other solutions offered were off by one day.
If you want Sunday to Saturday for last week, this is the way to do it.
$start = date("Y-m-d",strtotime("last sunday",strtotime("-1 week")));
$end = date("Y-m-d",strtotime("saturday",strtotime("-1 week")));
echo $start. " to ".$end;
Carbon
$startOfTheWeek = Carbon::now()->subWeek(1)->startOfWeek();
$endOfTheWeek = Carbon::now()->subWeek(1)->endOfWeek();
From a specific date
$startOfTheWeek = Carbon::parse('2020-03-02')->subWeek(1)->startOfWeek();
$endOfTheWeek = Carbon::parse('2020-03-02')->subWeek(1)->endOfWeek();
Considering the week starts at Monday and ends at Sunday.
You can do this way.
First get the current timestamp and subtract the no.of days you want.
$curTime = time();
echo date("Y-m-d",$curTime);
echo "<br />";
echo date("Y-m-d",($curTime-(60*60*24*7)));
$lastWeekStartTime = strtotime("last sunday",strtotime("-1 week"));
$lastWeekEndTime = strtotime("this sunday",strtotime("-1 week"));
$lastWeekStart = date("Y-m-d",$lastWeekStartTime);
$lastWeekEnd = date("Y-m-d",$lastWeekEndTime);
In order to find the last week start date and end date you can follow up this code for doing it so.
It works on all intervals to find the date interval.
$Current = Date('N');
$DaysToSunday = 7 - $Current;
$DaysFromMonday = $Current - 1;
$Sunday = Date('d/m/y', strtotime("+ {$DaysToSunday} Days"));
$Monday = Date('d/m/y', strtotime("- {$DaysFromMonday} Days"));
If so you need to change it with the datatime() you can perform this function.
$date = new DateTime();
$weekday = $date->format('w');
$diff = 7 + ($weekday == 0 ? 6 : $weekday - 1); // Monday=0, Sunday=6
$date->modify("-$diff day");
echo $date->format('Y-m-d') . ' - ';
$date->modify('+6 day');
echo $date->format('Y-m-d');
Using Functions:
If you want to find the last week range with the help of the functions you can preform like this.
Function:
// returns last week's range
function last_week_range($date) {
$ts = strtotime("$date - 7 days");
$start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
return array(
date('Y-m-d', $start),
date('Y-m-d', strtotime('next saturday', $start))
);
}
Usage:
$today=date();
print_r(last_week_range($today));
All the above functions that has been given will return the last week range irrespective of the start day of the week..

Get first day of week in PHP?

Given a date MM-dd-yyyy format, can someone help me get the first day of the week?
Here is what I am using...
$day = date('w');
$week_start = date('m-d-Y', strtotime('-'.$day.' days'));
$week_end = date('m-d-Y', strtotime('+'.(6-$day).' days'));
$day contains a number from 0 to 6 representing the day of the week (Sunday = 0, Monday = 1, etc.).
$week_start contains the date for Sunday of the current week as mm-dd-yyyy.
$week_end contains the date for the Saturday of the current week as mm-dd-yyyy.
Very simple to use strtotime function:
echo date("Y-m-d", strtotime('monday this week')), "\n";
echo date("Y-m-d", strtotime('sunday this week')), "\n";
It differs a bit across PHP versions:
Output for 5.3.0 - 5.6.6, php7#20140507 - 20150301, hhvm-3.3.1 - 3.5.1
2015-03-16
2015-03-22
Output for 4.3.5 - 5.2.17
2015-03-23
2015-03-22
Output for 4.3.0 - 4.3.4
2015-03-30
2015-03-29
Comparing at Edge-Cases
Relative descriptions like this week have their own context. The following shows the output for this week monday and sunday when it's a monday or a sunday:
$date = '2015-03-16'; // monday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";
$date = '2015-03-22'; // sunday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";
Againt it differs a bit across PHP versions:
Output for 5.3.0 - 5.6.6, php7#20140507 - 20150301, hhvm-3.3.1 - 3.5.1
2015-03-16
2015-03-22
2015-03-23
2015-03-29
Output for 4.3.5 - 5.0.5, 5.2.0 - 5.2.17
2015-03-16
2015-03-22
2015-03-23
2015-03-22
Output for 5.1.0 - 5.1.6
2015-03-23
2015-03-22
2015-03-23
2015-03-29
Output for 4.3.0 - 4.3.4
2015-03-23
2015-03-29
2015-03-30
2015-03-29
strtotime('this week', time());
Replace time(). Next sunday/last monday methods won't work when the current day is sunday/monday.
Keep it simple :
<?php
$dateTime = new \DateTime('2020-04-01');
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dateTime->modify('Sunday this week');
?>
Source : PHP manual
NB: as some user commented the $dateTime value will be modified.
$givenday = date("w", mktime(0, 0, 0, MM, dd, yyyy));
This gives you the day of the week of the given date itself where 0 = Sunday and 6 = Saturday. From there you can simply calculate backwards to the day you want.
This question needs a good DateTime answer:-
function firstDayOfWeek($date)
{
$day = DateTime::createFromFormat('m-d-Y', $date);
$day->setISODate((int)$day->format('o'), (int)$day->format('W'), 1);
return $day->format('m-d-Y');
}
var_dump(firstDayOfWeek('06-13-2013'));
Output:-
string '06-10-2013' (length=10)
This will deal with year boundaries and leap years.
EDIT: the below link is no longer running on the version of PHP stated. It is running on PHP 5.6 which improves the reliability of strtotime, but isn't perfect! The results in the table are live results from PHP 5.6.
For what it's worth, here is a breakdown of the wonky behavior of strtotime when determining a consistent frame of reference:
http://gamereplays.org/reference/strtotime.php
Basically only these strings will reliably give you the same date, no matter what day of the week you're currently on when you call them:
strtotime("next monday");
strtotime("this sunday");
strtotime("last sunday");
Assuming Monday as the first day of the week, this works:
echo date("M-d-y", strtotime('last monday', strtotime('next week', time())));
The following code should work with any custom date, just uses the desired date format.
$custom_date = strtotime( date('d-m-Y', strtotime('31-07-2012')) );
$week_start = date('d-m-Y', strtotime('this week last monday', $custom_date));
$week_end = date('d-m-Y', strtotime('this week next sunday', $custom_date));
echo '<br>Start: '. $week_start;
echo '<br>End: '. $week_end;
I tested the code with PHP 5.2.17 Results:
Start: 30-07-2012
End: 05-08-2012
How about this?
$first_day_of_week = date('m-d-Y', strtotime('Last Monday', time()));
$last_day_of_week = date('m-d-Y', strtotime('Next Sunday', time()));
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');
Here I am considering Sunday as first & Saturday as last day of the week.
$m = strtotime('06-08-2012');
$today = date('l', $m);
$custom_date = strtotime( date('d-m-Y', $m) );
if ($today == 'Sunday') {
$week_start = date("d-m-Y", $m);
} else {
$week_start = date('d-m-Y', strtotime('this week last sunday', $custom_date));
}
if ($today == 'Saturday') {
$week_end = date("d-m-Y", $m);
} else {
$week_end = date('d-m-Y', strtotime('this week next saturday', $custom_date));
}
echo '<br>Start: '. $week_start;
echo '<br>End: '. $week_end;
Output :
Start: 05-08-2012
End: 11-08-2012
How about this?
$day_of_week = date('N', strtotime($string_date));
$week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
$week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));
Just use date($format, strtotime($date,' LAST SUNDAY + 1 DAY'));
Try this:
function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y')
{
$wk_ts = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
$mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
return date($format, $mon_ts);
}
$sStartDate = week_start_date($week_number, $year);
$sEndDate = date('F d, Y', strtotime('+6 days', strtotime($sStartDate)));
(from this forum thread)
This is the shortest and most readable solution I found:
<?php
$weekstart = strtotime('monday this week');
$weekstop = strtotime('sunday this week 23:59:59');
//echo date('d.m.Y H:i:s', $weekstart) .' - '. date('d.m.Y H:i:s', $weekstop);
?>
strtotime is faster than new DateTime()->getTimestamp().
$monday = date('d-m-Y',strtotime('last monday',strtotime('next monday',strtotime($date))));
You have to get next monday first then get the 'last monday' of next monday. So if the given date is monday it will return the same date not last week monday.
$string_date = '2019-07-31';
echo $day_of_week = date('N', strtotime($string_date));
echo $week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
echo $week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));
Given PHP version pre 5.3 following function gives you a first day of the week of given date (in this case - Sunday, 2013-02-03):
<?php
function startOfWeek($aDate){
$d=strtotime($aDate);
return strtotime(date('Y-m-d',$d).' - '.date("w",$d).' days');
}
echo(date('Y-m-d',startOfWeek("2013-02-07")).'
');
?>
$today_day = date('D'); //Or add your own date
$start_of_week = date('Ymd');
$end_of_week = date('Ymd');
if($today_day != "Mon")
$start_of_week = date('Ymd', strtotime("last monday"));
if($today_day != "Sun")
$end_of_week = date('Ymd', strtotime("next sunday"));
If you want Monday as the start of your week, do this:
$date = '2015-10-12';
$day = date('N', strtotime($date));
$week_start = date('Y-m-d', strtotime('-'.($day-1).' days', strtotime($date)));
$week_end = date('Y-m-d', strtotime('+'.(7-$day).' days', strtotime($date)));
A smart way of doing this is to let PHP handle timezone differences and Daylight Savings Time (DST). Let me show you how to do this.
This function will generate all days from Monday until Friday, inclusive (handy for generating work week days):
class DateTimeUtilities {
public static function getPeriodFromMondayUntilFriday($offset = 'now') {
$now = new \DateTimeImmutable($offset, new \DateTimeZone('UTC'));
$today = $now->setTime(0, 0, 1);
$daysFromMonday = $today->format('N') - 1;
$monday = $today->sub(new \DateInterval(sprintf('P%dD', $daysFromMonday)));
$saturday = $monday->add(new \DateInterval('P5D'));
return new \DatePeriod($monday, new \DateInterval('P1D'), $saturday);
}
}
foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday() as $day) {
print $day->format('c');
print PHP_EOL;
}
This will return datetimes Monday-Friday for current week. To do the same for an arbitrary date, pass a date as a parameter to DateTimeUtilities ::getPeriodFromMondayUntilFriday, thus:
foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00') as $day) {
print $day->format('c');
print PHP_EOL;
}
//prints
//2017-01-02T00:00:01+00:00
//2017-01-03T00:00:01+00:00
//2017-01-04T00:00:01+00:00
//2017-01-05T00:00:01+00:00
//2017-01-06T00:00:01+00:00
Only interested in Monday, as the OP asked?
$monday = DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00')->getStartDate()->format('c');
print $monday;
// prints
//2017-01-02T00:00:01+00:00
You parse the date using strptime() and use date() on the result:
date('N', strptime('%m-%d-%g', $dateString));
<?php
/* PHP 5.3.0 */
date_default_timezone_set('America/Denver'); //Set apprpriate timezone
$start_date = strtotime('2009-12-15'); //Set start date
//Today's date if $start_date is a Sunday, otherwise date of previous Sunday
$today_or_previous_sunday = mktime(0, 0, 0, date('m', $start_date), date('d', $start_date), date('Y', $start_date)) - ((date("w", $start_date) ==0) ? 0 : (86400 * date("w", $start_date)));
//prints 12-13-2009 (month-day-year)
echo date('m-d-Y', $today_or_previous_sunday);
?>
(Note: MM, dd and yyyy in the Question are not standard php date format syntax - I can't be sure what is meant, so I set the $start_date with ISO year-month-day)
I've come against this question a few times and always surprised the date functions don't make this easier or clearer. Here's my solution for PHP5 that uses the DateTime class:
/**
* #param DateTime $date A given date
* #param int $firstDay 0-6, Sun-Sat respectively
* #return DateTime
*/
function getFirstDayOfWeek(DateTime $date, $firstDay = 0) {
$offset = 7 - $firstDay;
$ret = clone $date;
$ret->modify(-(($date->format('w') + $offset) % 7) . 'days');
return $ret;
}
Necessary to clone to avoid altering the original date.
Another way to do it....
$year = '2014';
$month = '02';
$day = '26';
$date = DateTime::createFromFormat('Y-m-d H:i:s', $year . '-' . $month . '-' . $day . '00:00:00');
$day = date('w', $date->getTimestamp());
// 0=Sunday 6=Saturday
if($day!=0){
$newdate = $date->getTimestamp() - $day * 86400; //86400 seconds in a day
// Look for DST change
if($old = date('I', $date->getTimestamp()) != $new = date('I', $newdate)){
if($old == 0){
$newdate -= 3600; //3600 seconds in an hour
} else {
$newdate += 3600;
}
}
$date->setTimestamp($newdate);
}
echo $date->format('D Y-m-d H:i:s');
The easiest way to get first day(Monday) of current week is:
strtotime("next Monday") - 604800;
where 604800 - is count of seconds in 1 week(60*60*24*7).
This code get next Monday and decrease it for 1 week. This code will work well in any day of week. Even if today is Monday.
I found this quite frustrating given that my timezone is Australian and that strtotime() hates UK dates.
If the current day is a Sunday, then strtotime("monday this week") will return the day after.
To overcome this:
Caution: This is only valid for Australian/UK dates
$startOfWeek = (date('l') == 'Monday') ? date('d/m/Y 00:00') : date('d/m/Y', strtotime("last monday 00:00"));
$endOfWeek = (date('l') == 'Sunday') ? date('d/m/Y 23:59:59') : date('d/m/Y', strtotime("sunday 23:59:59"));
Here's a one liner for the first day of last week, and the last day of last week as a DateTime object.
$firstDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 7))
->setTime(0, 0, 0);
$lastDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 1))
->setTime(23, 59, 59);
Just to note that timestamp math can also be a solution. If you have in mind that 01.jan 1970 was a Thursday, then start of a week for any given date can be calculated with:
function weekStart($dts)
{ $res = $dts - ($dts+date('Z',$dts)+259200)%604800;
return $res + 3600*(date('I',$dts)-date('I',$res));
}
It is predictable for any timestamp and php version, using date-func ('Z', 'I') only for timezone and daylight-saving offsets. And it produces same results as:
strtotime(date('Y-m-d', $dts).' - '.(date('N', $dts)-1.' days');
and with (the best and the most elegant) mentioned:
strtotime('monday this week', $dts);

Categories