我正在尝试根据区域设置查找第一天和上周的日期。 在美国周日开始,但在其他国家,它可能在星期一甚至星期六开始。
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
}
答案 0 :(得分:8)
执行此操作的一种方法是使用IntlCalendar类。它有一个方法getFirstDayofWeek(),它返回一个整数,对应IntlCalendar中的 DOW _ 常量:
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 ;
使用它可以在开始日调用DateTimeImmutable::modify()
时将天数添加到开始日期。在this phpfiddle中使用三种语言环境(即 en_US , es_ES , sw_KE )查看它的实际效果。
$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('l m/d/Y').'<br />';
}