4

I want to convert Gregorian date time to Persian date time. Here is my code :

public function convertToJalali(DateTime $gregorianDateTime)
{
    if ($gregorianDateTime->year < 1) {
        $gregorianDateTime = new DateTime('1970-01-01');
    }

    $this->dateTime['gregorian'] = $gregorianDateTime;

    $fmt = new \IntlDateFormatter(
        'en_US@calendar=gregorian',
        IntlDateFormatter::SHORT, //date format
        IntlDateFormatter::NONE, //time format
        'UTC',
        IntlDateFormatter::TRADITIONAL,
        'yyyy/MM/dd HH:mm:ss'
    );
    $time = $fmt->parse($gregorianDateTime);


    $formatter = \IntlDateFormatter::create(
        "en_US@calendar=persian",
        IntlDateFormatter::FULL,
        IntlDateFormatter::FULL,
        'Asia/Tehran',
        IntlDateFormatter::TRADITIONAL,
        'yyyy/MM/dd HH:mm:ss'
    );
    try {
        $this->dateTime['jalali'] = new DateTime($formatter->format($time));
        $this->dateTime['jalali']->setTimeZone(new \DateTimeZone('Asia/Tehran'));

    } catch (\Exception $ex) {
        $this->dateTime['jalali'] = new DateTime(date('Y-m-d H:i:s'), new \DateTimeZone('Asia/Tehran'));

    }
    return $this;
}

Everything is working like a charm except last day of month, for example second Persian calendar has 31 days however second gregorian date time has 28 days , when date is equal to 29 (in persian) it convert it to first day of third month wrongly. Any suggestion?

Farzan Najipour
  • 2,442
  • 7
  • 42
  • 81
  • Look at here. You can use this library : https://stackoverflow.com/questions/30377948/convert-date-and-time-to-jalali-in-laravel/49523574#49523574 – Roham Rafii Jan 20 '19 at 20:06

0 Answers0