在PHP中检索日期名称 [英] Retrieving Day Names in PHP

查看:112
本文介绍了在PHP中检索日期名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向用户显示一个表单中的本地化日期名称列表(如星期一,星期二,...)。我知道要得到任何日期的日期名称。但是,有没有一个特殊的和失败的方法来获取数组中的所有日期名称。

I need to display to user a list of localized day names (like 'Monday', 'Tuesday', ...) in a form. I know ho to get day name of any date. But is there a particular and fail-proof way to get all day names in an array.

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

I could add names of days to my translation file but that is hard to maintain.

推荐答案

使用 strftime() 结合 setlocale() 是一个选项。

Using strftime() in combination with setlocale() is an option.

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

However you should be aware that on threaded php installs, setlocale() can behave unexpected, since locale information is maintained per process, not per thread. Therefor it is important to call setlocale() every time before each call to strftime() to guarantee it uses the correct locale.

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

Also, for Windows systems, you need to use somewhat unusual strings for the $locale parameter for setlocale().

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

See the docs for more information on both of these issues.

这样的东西应该可以工作:

Something like this should work:

// 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 );

这篇关于在PHP中检索日期名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆