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"));
Try this. echo date('Y-m-d', strtotime('last monday', strtotime('next monday'))); It will return current date if today is monday, and will return last monday otherwise.
just used it - date('Y-m-d H:i:s', strtotime('+1 week')); works fine in PHP 7 to give one week from now.
How to get the week number from a date. To get the ISO week number (1-53) of a date represented by a Unix timestamp, use idate('W', $timestamp ) or strftime('%-V', $timestamp ) .
$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 answer returns whether a given date is sunday or monday etc.
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.
Best solution would be:
$monday = date( 'Y-m-d', strtotime( 'monday this week' ) ); $friday = date( 'Y-m-d', strtotime( 'friday this week' ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With