Php 在某些日子里从公历转换成波斯历是错误的
我想在代码中使用PHP的IntlDateFormatter来使用波斯日历。 这几天PHP有内置函数,支持波斯日历,工作正常,但我在某些日子遇到了问题 例如,使用此代码,所有日期从格里高利转换为波斯语,直到2018-3-17转换为“1396-12-26”,之后,2018-3-18转换为“1397-12-27”,我不知道为什么年份会增加 我的php代码:Php 在某些日子里从公历转换成波斯历是错误的,php,datetime,persian,intl,Php,Datetime,Persian,Intl,我想在代码中使用PHP的IntlDateFormatter来使用波斯日历。 这几天PHP有内置函数,支持波斯日历,工作正常,但我在某些日子遇到了问题 例如,使用此代码,所有日期从格里高利转换为波斯语,直到2018-3-17转换为“1396-12-26”,之后,2018-3-18转换为“1397-12-27”,我不知道为什么年份会增加 我的php代码: class MyDateTime extends \DateTime { protected $calendar='gre
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";
不知道为什么你的代码不起作用。旧的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>';
}
谢谢你的回复,你也测试过我的代码吗?在公历和波斯历之间切换时,它可能会累积?
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