简体   繁体   中英

How to detect if first day of the week is Saturday, Sunday, or Monday?

What is a dependancy free solution for my PHP application to detect the first day of the week for the running php process? Example:

  • Saturday (Middle-Eastern week calendar)
  • Sunday (Western week calendar)
  • Monday (ISO-8601 week calender).

I have tried this:

$first_day_of_week = date('l', strtotime('This week'));

I expected the code to return Sunday for american users and Monday for european. But it always returns Monday (an ISO-8601 week calendar).

Athough not a dependancy free solution. Here is detecting week type using the PHP extension Intl.

if (extension_loaded('intl')) {
  switch (IntlCalendar::createInstance()->getFirstDayOfWeek()) {
    case 1: $first_day_of_week = 'Sunday'; break; // Western
    case 2: $first_day_of_week = 'Monday'; break; // ISO-8601
    case 7: $first_day_of_week = 'Saturday'; break; // Middle Eastern
  }
} else {
  trigger_error('PHP is missing the Intl extension', E_USER_WARNING);
}

The first day of the week returned by

$no = IntlCalendar::createInstance()->getFirstDayOfWeek();

depends on your php.ini. You get the default value with locale_get_default(). IntlCalendar::createInstance() accepts a locale as the 2nd parameter, which then delivers different results for the first day of the week.

foreach(['en_AE','en_US','en_GB'] as $locale){
  $no = IntlCalendar::createInstance(null,$locale)->getFirstDayOfWeek();
  $weekDayName = date('l', strtotime('Saturday +'.$no.' days'));
  echo $locale.' : '.$weekDayName.'<br>';
}

Output:

en_AE : Saturday
en_US : Sunday
en_GB : Monday

Regardless of this, the following applies for date and DateTime:

Start of week is always ISO-8601 in PHP date functions.

(as already noted in the comment)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM