0

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
d.raev
  • 9,216
  • 8
  • 58
  • 79
  • What version of php are you running? – Anthony Mar 10 '15 at 12:31
  • 3
    @Cory not in my country and in half the world the business week starts in Monday. – d.raev Mar 10 '15 at 12:34
  • 1
    Have you seen: http://stackoverflow.com/q/13128854/74757 or http://stackoverflow.com/q/1897727/74757 ? – Cᴏʀʏ Mar 10 '15 at 12:36
  • My php Installation is with default settings, and making my code rely on custom settings, will make it harder for support when moved to another server or distributed. – d.raev Mar 10 '15 at 12:42
  • 1
    As its documentation clearly states, the function [`strtotime()`](http://php.net/manual/en/function.strtotime.php) parses **English** textual datetime description. It doesn't care about locales, it understands only the English formats (British and American). Since English week always starts on Sunday your approach is doomed to fail. And, yes, `strtotime()` works well (in case you wonder). If it doesn't return the date you expect, take a closer look at the [`relative date&time formats`](http://php.net/manual/en/datetime.formats.relative.php). It explains how `strtotime()` interprets the input. – axiac Mar 10 '15 at 12:47
  • 1
    A PECL library that might be useful for this purpose http://php.net/manual/en/intlcalendar.getfirstdayofweek.php but since you're looking to reduce configuration, there might be a good composer lib you could use. That has a similar function. – Brian Moore Mar 10 '15 at 12:52

1 Answers1

1

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");
axiac
  • 68,258
  • 9
  • 99
  • 134