【发布时间】:2017-09-06 00:55:47
【问题描述】:
PHP intl 可以将公历日期转换为其他日历类型。
例如公历到回历,2017/04/11 到 1396/01/22
或者我们必须使用外部库来转换日期?
【问题讨论】:
标签: php intl datetime-conversion hijri
PHP intl 可以将公历日期转换为其他日历类型。
例如公历到回历,2017/04/11 到 1396/01/22
或者我们必须使用外部库来转换日期?
【问题讨论】:
标签: php intl datetime-conversion hijri
你可以使用这个方法:
function getDateTimeFromCalendarToFormat($format = 'yyyy-MM-dd HH:mm:ss', $time = null, $locale = 'fa_IR', $calendar = 'persian', $timeZone = 'Asia/Tehran')
{
if (empty($time)) {
$time = new \DateTime();
}
$formatter = new \IntlDateFormatter("{$locale}@calendar={$calendar}", \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, $timeZone, \IntlDateFormatter::TRADITIONAL);
$dateArray = [];
$formatter->setPattern($format);
return $formatter->format($time);
}
如果您致电getDateTimeFromCalendarToFormat('yyyy-MM-dd HH:mm:ss',null,'en_US')
返回1396-06-27 13:50:21
如果您致电getDateTimeFromCalendarToFormat('yyyy-MM-dd HH:mm:ss',null,'fa_IR')
返回۱۳۹۶-۰۶-۲۷ ۱۳:۴۹:۵۱
要使用的新模式字符串。可能的模式记录在Formatting Dates and Times
【讨论】:
是的,它可以。这是一个使用 intl 将时间对象转换为其波斯格式字符串的示例:
function c2persian($time, $toCalender = 'persian', $timezone = 'Asia/Tehran', $locale = 'fa_IR') {
$formatter = IntlDateFormatter::create($locale, NULL, NULL, $timezone, IntlCalendar::createInstance($timezone, "$locale@calendar=$toCalender"));
return $formatter->format($time);
}
$time = strtotime("2089-08-09 00:00:00 UTC");
echo c2persian($time);
您可以在php intlCalendar documentation找到更多信息。
【讨论】:
PHP已有日期格式功能,需要先用strtotime()函数转换,再用date()得到想要的值
<?php
$originalDate = "2017/04/11";
$theDate = strtotime($originalDate);
$theDay = date('d',$theDate);
$theMonth = date('m',$theDate);
$theYear = date('Y',$theDate);
$customFormat = date('Y-m-d',$theDate);
$customFormat2 = date('d/m/Y',$theDate);
$customFormat3 = date('F j, Y, g:i a',$theDate);
?>
此处的示例:https://eval.in/772416
您可以在此处获取有关 php 日期的更多信息:http://php.net/manual/en/function.date.php
【讨论】: