Get date for monday and friday for the current week (PHP)
How can I get the date for monday and friday for the current week?
I have the following code, but it fails if current day is sunday or saturday.
$current_day = date("N");
$days_to_friday = 5 - $current_day;
$days_from_monday = $current_day - 1;
$monday = date("Y-m-d", strtotime("- {$days_from_monday} Days"));
$friday = date("Y-m-d", strtotime("+ {$days_to_friday} Days"));
Best solution would be:
$monday = date( 'Y-m-d', strtotime( 'monday this week' ) );
$friday = date( 'Y-m-d', strtotime( 'friday this week' ) );
These strtotime inputs work very well:
strtotime( "next monday" );
strtotime( "previous monday" );
strtotime( "today" );
strtotime( "next friday" );
strtotime( "previous friday" );
All you need to do is to wrap the logic inside some if statements.
This question needs a DateTime answer:-
/**
* @param String $day
* @return DateTime
*/
function getDay($day)
{
$days = ['Monday' => 1, 'Tuesday' => 2, 'Wednesday' => 3, 'Thursday' => 4, 'Friday' => 5, 'Saturday' => 6, 'Sunday' => 7];
$today = new \DateTime();
$today->setISODate((int)$today->format('o'), (int)$today->format('W'), $days[ucfirst($day)]);
return $today;
}
Usage:
var_dump(getDay('Monday')->format('l dS F Y'));
var_dump(getDay('Friday')->format('l dS F Y'));
Output:
string 'Monday 30th September 2013' (length=26)
string 'Friday 04th October 2013' (length=24)
See it working
i use :
$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 + 4 days', strtotime('this sunday')));
This really depends on how you define a week but I came up with this function that will give you the date for the nearest "monday" or "friday" (or any day for that matter):
function closestDate($day){
$day = ucfirst($day);
if(date('l', time()) == $day)
return date("Y-m-d", time());
else if(abs(time()-strtotime('next '.$day)) < abs(time()-strtotime('last '.$day)))
return date("Y-m-d", strtotime('next '.$day));
else
return date("Y-m-d", strtotime('last '.$day));
}
Input: a day of the week ("sunday", "Monday", etc.)
Output: If I asked for the nearest "sunday" and today is:
- "Sunday": I will get today's date
- "Monday": I will get yesterday's date
- "Saturday: I will get tomorrow's date
Hope this helps :)