phpwordpresscalendarhijri

how to write a funtion to get each regions date by calling it in it's own language?


I'm in wordpress and write some php to get Pesrian and Arabic date from Gregorian. And I see this: Formatting DateTime object, respecting Locale::getDefault()

I want a function to get persian and arabic date each time function calls by simply change region and timezone


Solution

  • You can't use languages other than English with the standard date/DateTime constructs in PHP. The only way to do this was to set the locale using setlocale() and use the strfttime() function... however that function is now deprecated in favor of using the INTL/ICU extension's IntlDateFormatter class:

    function getFormattedDateIntl(
        ?\DateTime $date = null,
        ?string $locale = null,
        ?DateTimeZone $timezone = null,
        string $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);
    }
    
    function getWeekdayIntl(
        ?\DateTime $date = null,
        ?string $locale = null,
        ?DateTimeZone $timezone = null
    ) {
        return getFormattedDateIntl($date, $locale, $timezone, 'eeee');
    }
    
    $islamicDateRight = getFormattedDateIntl(
        new DateTime(),
        'ar@calendar=islamic-civil',
        new \DateTimeZone('Asia/Tehran'),
        'eeee dd MMMM'
    );