在PHP中检索日期名称

Cem*_*ker 11 php locale date

我需要向用户显示表单中的本地化日期名称列表(如"星期一","星期二"......).我知道要获得任何日期的日期名称.但是有没有一种特殊的,防止故障的方法来获取阵列中的全天名称.

编辑:我可以在我的翻译文件中添加天数,但这很难维护.

Abb*_*bas 33

$date = '2011/10/14'; 
$day = date('l', strtotime($date));
echo $day;
Run Code Online (Sandbox Code Playgroud)


Dec*_*ler 14

使用strftime()与组合setlocale()是一个选项.

但是,您应该知道,在线程php安装上,setlocale()可能会出现意外情况,因为每个进程维护的是区域设置信息,而不是每个线程.因此,setlocale()每次调用之前每次调用都很重要,strftime()以保证它使用正确的语言环境.

此外,对于Windows系统,您需要为$locale参数使用一些不常见的字符串setlocale().

有关这两个问题的更多信息,请参阅文档.

这样的事情应该有效:

// define the locales for setlocale() for which we need the daynames
$locales = array(
  'en_EN',
  'de_DE',
  'nl_NL'
  // etc...
);

// be aware that setlocale() needs different values on Windows machines
// see the docs on setlocale() for more information
$locales = array(
  'english',
  'german',
  'dutch'
  // etc...
);

// let's remember the current local setting
$oldLocale = setlocale( LC_TIME, '0' );

// initialize out result array
$localizedWeekdays = array();

// loop each locale
foreach( $locales as $locale )
{
    // create sub result array for this locale 
    $localizedWeekdays[ $locale ] = array();

    // 7 days in a week
    for( $i = 0; $i < 7; $i++ )
    {
        // set the locale on each iteration again
        setlocale( LC_TIME, $locale );

        // combine strftime() with the nifty strtotime()
        $localizedWeekdays[ $locale ][] = strftime( '%A', strtotime( 'next Monday +' . $i . ' days' ) );

        // reset the locale for other threads, as a courtesy
        setlocale( LC_TIME, $oldLocale );
    }
}

// there is your result in a multi-dimensional array
var_dump( $localizedWeekdays );
Run Code Online (Sandbox Code Playgroud)


yck*_*art 5

“通常”的方法是从给定的开始last day并在每次迭代中计算一天。

for ($i = 0; $i < 7; $i++) {
  $weekDayNames[] = strftime("%a", strtotime("last sunday +$i day"));
}
Run Code Online (Sandbox Code Playgroud)