在某些日子里错误地从格里高利转换到波斯日历

时间:2018-02-19 11:20:12

标签: php datetime persian intl

我想使用PHP的IntlDateFormater在我的代码中使用波斯语日历。 这几天PHP有内置函数,它们可以支持波斯语日历并且工作正常但我在某些日子里遇到了问题。

例如使用此代码所有日期都将从格里高利转换为波斯语,直到日期2018-3-17转换为“1396-12-26”,之后,日期2018-3-18转换为“1397-12-” 27“我不知道为什么年份会增加?

我的PHP代码:

INSERT INTO TableX (id, field1, field2, zip, field3) 
SELECT NULL, @val1, @val2, zipcode, @val3
FROM TableY

输出:

class MyDateTime extends \DateTime {
            protected $calendar='gregorian';
            protected $timezone;
            public function __construct() {     
                $timezone = new \DateTimeZone('Asia/Tehran');
                $this->timezone = $timezone;
                parent::__construct(null, $timezone);
                $this->setCalendar('gregorian');
                $this->modify('2018-2-19');
            }   
            public function setCalendar($calendar) {
                $this->calendar = strtolower($calendar);
                return $this;
            }   
            public function format($pattern){
                $formater = new \IntlDateFormatter('en_US' . '@calendar=' . $this->calendar,
                        \IntlDateFormatter::FULL,  \IntlDateFormatter::FULL, $this->timezone,
                        $this->calendar == 'gregorian' ? \IntlDateFormatter::GREGORIAN : \IntlDateFormatter::TRADITIONAL, $pattern);
                return $formater->format(parent::format('U'));

            }   
        }
        $d = new MyDateTime();
        $d->setCalendar('gregorian');
        echo $d->format('Y-M-d');
         $d->setCalendar('persian');
        echo " Persian: ".$d->format('Y-M-d')."<br >\n";

        echo 'Next mpnth:'." <br>\n";
        $d->modify('+26 day');

        $d->setCalendar('gregorian');
        echo $d->format('Y-M-d');
        $d->setCalendar('persian');
        echo " Persian: ".$d->format('Y-M-d')."<br >\n";            

        echo 'Next day:'." <br>\n";
        $d->modify('+1 day');

        $d->setCalendar('gregorian');
        echo $d->format('Y-M-d');
        $d->setCalendar('persian');
        echo " Persian: ".$d->format('Y-M-d')."<br >\n";

1 个答案:

答案 0 :(得分:1)

不知道为什么您的代码不起作用。旧的PHP版本?可以在PHP 7.2.21上正常工作:

function dateGregorianToPersian($strDate)
{
  $tz = new DateTimeZone('Asia/Tehran');
  $fmt = datefmt_create(
    "ir_IR@calendar=persian", 
    IntlDateFormatter::FULL, 
    IntlDateFormatter::FULL, 
    $tz, 
    IntlDateFormatter::TRADITIONAL,
    "yyyy-MM-dd"
  );
  return datefmt_format( $fmt ,date_create($strDate,$tz));
}

//test
$data = ['2018-2-19','2018-3-17','2018-3-18'];
foreach($data as $strDate){
  echo $strDate.' Persian: '.dateGregorianToPersian($strDate).'<br>';
}

输出

2018-2-19 Persian: 1396-11-30
2018-3-17 Persian: 1396-12-26
2018-3-18 Persian: 1396-12-27