Gregorian to persian calendar convert - change month output from finglish to perisan

230 Views Asked by At

In wordpress I already convert correctly th gregorian date to persian but my code returns perisan month in english (finglish) for example it returns Farvardin instead of فروردین.and other 11 months too.

this is my code so far.

$now = new DateTime();
$formatterMonth = new IntlDateFormatter(
  "en_US@calendar=persian",
  IntlDateFormatter::FULL,
  IntlDateFormatter::FULL,
  'Asia/Tehran',
  IntlDateFormatter::TRADITIONAL,
  "dd MMMM",
);
echo $formatterMonth->format($now); //output ۲۹ Farvardin
2

There are 2 best solutions below

0
Alipvd On BEST ANSWER

Kamyar your answere is right but I found shorter way to do that.

function getDateIntl(?\DateTime $date = null, ?string $locale = null, ?DateTimeZone 
    $timezone = null, $dateFormat) {
    $date = $date ?? new \DateTime();
    $locale = $locale ?? \Locale::getDefault();
    $formatter = new \IntlDateFormatter(
      $locale,
      IntlDateFormatter::FULL,
      IntlDateFormatter::FULL,
      $timezone,
      IntlDateFormatter::TRADITIONAL,
      $dateFormat
  );
 return $formatter->format($date);
}
 $persianDateRight = getDateIntl(new DateTime(), "fa@calendar=persian", new \DateTimeZone('Asia/Tehran'), 'eeee، dd MMMM');

this way no need to loop inside the array. and also can change to any language and timezone and time format

0
Kamyar Safari On

To convert Gregorian date to Shamsi(Jalali), it is better to use JDF or Morilog library

the Morilog library: https://github.com/morilog/jalali/

But if you still want to use your own code, you can easily convert finglish months to farsi:

<?php
$now = new DateTime();
$formatterMonth = new IntlDateFormatter(
  "en_US@calendar=persian",
  IntlDateFormatter::FULL,
  IntlDateFormatter::FULL,
  'Asia/Tehran',
  IntlDateFormatter::TRADITIONAL,
  "dd MMMM",
);
$myDate = $formatterMonth->format($now); //output ۲۹ Farvardin

$monthArray = [
    'Farvardin' => 'فروردین',
    'Ordibehesht' => 'اردیبهشت',
    'Khordad' => 'خرداد',
    'Tir' => 'تیر',
    'Mordad' => 'مرداد',
    'Shahrivar' => 'شهریور',
    'Mehr' => 'مهر',
    'Aban' => 'آبان',
    'Azar' => 'آذر',
    'Dey' => 'دی',
    'Bahman' => 'بهمن',
    'Esfand' => 'اسفند',
];

$explodedDate = explode(" ",$myDate);
$myFinglishMonth = $explodedDate[1];
$myFarsiMonth = $monthArray[$myFinglishMonth];

$convertedFarsiDate = $explodedDate[0]." ".$myFarsiMonth;

echo $convertedFarsiDate;

I hope this helps you