Find the days of the first and last week according to the language

I am trying to find the days of the first and last week based on the language. In the United States, a week starts on Sunday, but in other countries it can start on Monday or even Saturday.

setlocale(LC_ALL, "en_US.UTF-8"); date_default_timezone_set("America/New_York"); $start_week = (new DateTimeImmutable()); $start_week = $start_week->modify('this week'); $end_week = $start_week->modify('this week +6 days'); $interval = new DateInterval('P1D'); $week_range = new DatePeriod($start_week, $interval, $end_week); foreach($week_range as $week_day) { // $week_day starts with Monday, supposed to be Sunday } 
+6
source share
1 answer

One way to do this is to use the IntlCalendar class. It has a getFirstDayofWeek () method that returns an integer corresponding to the DOW _ constants in IntlCalendar :

  const integer DOW_SUNDAY = 1;
 const integer DOW_MONDAY = 2;
 const integer DOW_TUESDAY = 3;
 const integer DOW_WEDNESDAY = 4;
 const integer DOW_THURSDAY = 5;
 const integer DOW_FRIDAY = 6;
 const integer DOW_SATURDAY = 7; 

Use this to add days to the start day when calling DateTimeImmutable::modify() for the start day. See it in action with three locales (i.e. en_US, es_ES, sw_KE) in this phpfiddle .

 $locale = 'es_ES'; //Spain Spanish locale $cal1 = IntlCalendar::createInstance(NULL, $locale); $firstDayOfWeek = $cal1->getFirstDayOfWeek(); $daysToAdd = $firstDayOfWeek - 2; //difference from US M-Sunday echo 'locale: '.$local.' first day of week: '.$cal1->getFirstDayOfWeek().' days to add: '.$daysToAdd.'<br />'; $start_week = new DateTimeImmutable(); $start_week = $start_week->modify('this week +'.$daysToAdd.' days'); $end_week = $start_week->modify('+6 days'); $interval = new DateInterval('P1D'); $week_range = new DatePeriod($start_week, $interval, $end_week); foreach($week_range as $week_day) { echo 'week day: '.$week_day->format('lm/d/Y').'<br />'; } 
+8
source

Source: https://habr.com/ru/post/1012766/


All Articles