PHP intl can convert a Gregorian date to other calendar type

烂漫一生 提交于 2019-11-30 09:37:41

问题


PHP intl can convert a Gregorian date to other calendar type.

For example Gregorian to Hijri, 2017/04/11 to 1396/01/22

Or we must use external library to convert dates?


回答1:


You Can Use This Method:

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

if you call getDateTimeFromCalendarToFormat('yyyy-MM-dd HH:mm:ss',null,'en_US')
Return
1396-06-27 13:50:21

if you call getDateTimeFromCalendarToFormat('yyyy-MM-dd HH:mm:ss',null,'fa_IR')
Return
۱۳۹۶-۰۶-۲۷ ۱۳:۴۹:۵۱

New pattern string to use. Possible patterns are documented at Formatting Dates and Times




回答2:


Yes it can. This is an example which converts a time object to its Persian formatted string using 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);

You can find more info at php intlCalendar documentation.




回答3:


PHP Already has date format functions, you need to convert first with strtotime() function and get the desired values with 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);
?>

Example working here: https://eval.in/772416

You can get more info about date in php here: http://php.net/manual/en/function.date.php



来源:https://stackoverflow.com/questions/43332341/php-intl-can-convert-a-gregorian-date-to-other-calendar-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!