d.raev
d.raev

Reputation: 9546

start and end of the week by given date

Is there a short preset function to find the start (Monday) and end (Sunday) of the week by a given $date ?

I tried: 1)

date("Y-m-d", strtotime('sunday this week ' . $date));
date("Y-m-d", strtotime('monday this week ' . $date));

But this fails when $date is Sunday... it returns the Monday of Next week.

2) also this

date("Y-m-d", strtotime('last monday ' . $date));
date("Y-m-d", strtotime('next sunday ' . $date));

But again if $date is Monday or Sunday it gives the previous/next week.

I know it can be done with few condition .. but I m look for more out of the box solution.

Upvotes: 0

Views: 124

Answers (1)

axiac
axiac

Reputation: 72186

You can use DateTime::format('N') to get the ISO-8601 day of the week (1 = Monday .. 7 = Sunday) and do some simple date arithmetic to get the Monday and the Sunday of the week that contains the specified date (I assume you want the week starting on Monday).

// Today (or any other day you like)
$today = new DateTime('now');
echo('Today:  '.$today->format('Y-m-d (D)')."\n");

// Day of week (1 = Monday .. 7 = Sunday)
$dow = $today->format('N');

// Monday is ($dow-1) days in the past
$monday = clone $today;
$monday->sub(new DateInterval('P'.($dow-1).'D'));
echo('Monday: '.$monday->format('Y-m-d')."\n");

// Sunday is 6 days after Monday
$sunday = clone $monday;
$sunday->add(new DateInterval('P6D'));
echo('Sunday: '.$sunday->format('Y-m-d')."\n");

Upvotes: 1

Related Questions