【问题标题】:Converting non-Gregorian dates using IntlDateFormatter使用 IntlDateFormatter 转换非公历日期
【发布时间】:2014-06-04 16:30:58
【问题描述】:

我应该如何使用IntlDateFormatter 将非公历日期转换为其他日历类型。 我想将 "1392-01-02"persian 转换为 islamic 日历。我尝试了以下代码,但它没有转换日历:

$formatter = IntlDateFormatter::create('en_US@calendar=persian', IntlDateFormatter::FULL,
    IntlDateFormatter::FULL, 'Asia/Tokyo',IntlDateFormatter::TRADITIONAL,'yy-MM-dd');
$formatter->setCalendar(IntlDateFormatter::GREGORIAN);
echo $formatter->format($formatter->parse("1392-2-31"));

【问题讨论】:

  • 您不应该将第 5 个参数作为IntlDateFormatter::TRADITIONAL 传递吗?由于输入日期是非公历。
  • @MarcellFülöp "需要在 locale 中指定非公历。示例可能包括 locale="hi@calendar=BUDDHIST"。看来这个参数完全没用。

标签: php calendar intl


【解决方案1】:

将要转换的时间定义为IntlCalendar 的实例,并使用其set($year,$month,$day) 方法设置日期。

$time = IntlCalendar::createInstance("Asia/Tokyo", "en_US@calendar=persian");
$time->set(1392,2,31);

//alternative way to define time using parse

/**
These constants are used to specify different formats in the constructor for DateType 
and TimeType.

IntlDateFormatter::NONE (integer)
Do not include this element
IntlDateFormatter::FULL (integer)
Completely specified style (Tuesday, April 12, 1952 AD or 3:30:42pm PST)
IntlDateFormatter::LONG (integer)
Long style (January 12, 1952 or 3:30:32pm)
IntlDateFormatter::MEDIUM (integer)
Medium style (Jan 12, 1952)
IntlDateFormatter::SHORT (integer)
Most abbreviated style, only essential data (12/13/52 or 3:30pm)
*/

$fmt = new IntlDateFormatter(
    'en_US@calendar=persian',
    IntlDateFormatter::SHORT, //date format
    IntlDateFormatter::NONE, //time format
    'Asia/Tokyo',
    IntlDateFormatter::TRADITIONAL
);

$time = $fmt->parse('3/31/1392 AP');

$formatter = IntlDateFormatter::create("en_US@calendar=islamic",
  IntlDateFormatter::FULL, 
  IntlDateFormatter::FULL,
  'Asia/Tokyo', 
  IntlDateFormatter::TRADITIONAL);

print $formatter->format($time);
//Friday, Shaʻban 13, 1434 AH at 8:52:23 AM Japan Standard Time

【讨论】:

  • 谢谢。在您的解决方案中,我必须手动解析非公历日期。如何在非公历日期上使用 IntlDateFomatter 的 parse 方法?
  • @PHPst parse 方法将您限制为 FULLLONGMEDIUMSHORT 格式。我为SHORT 添加了一个示例
  • parse 不限于FULL,...。使用pattern 参数,您可以将其用于任何格式。我的问题是parse 似乎接受公历输入。
  • 如果您想使用与IntlCalendar 对象相同的时区、区域设置和日历类型进行格式化,使用IntlDateFormatter::formatObject() 会更简单。
  • APparse方法中是什么意思?
猜你喜欢
  • 2015-11-22
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
相关资源
最近更新 更多