Convert the post date to Jalali date in WordPress

187 Views Asked by At

I need to convert the date of my posts to the Jalali calendar.

This is the code I’m using to display the date of the posts in WordPress. I tried using some plugins to change the date but they did not work.

echo get_the_title()
    ? '<span>'.date( ' j ',strtotime($post->post_date)).'</span>'.date( '/F , Y',strtotime($post->post_date))
    : '<a href="'.get_the_permalink().'"><span>'.date( ' j ',strtotime($post->post_date)).'</span>'.date( '/F , Y',strtotime($post->post_date)).'</a>';
1

There are 1 best solutions below

0
volkerschulz On

You should probably use the IntlDateFormatter class inside a function.

function convertDateTime($datetimestr, $timezone='Asia/Tehran') {
    $timestamp = strtotime($datetimestr);

    $formatter = new IntlDateFormatter(
        'fa-IR',
        IntlDateFormatter::SHORT,
        IntlDateFormatter::SHORT,
        $timezone,
        IntlDateFormatter::TRADITIONAL,
    );

    return $formatter->format($timestamp);
}

And then echo convertDateTime($post->post_date) when showing your posts.

For 2023-10-14 12:00:00 this gives me ۱۴۰۲/۷/۲۲, ۱۵:۳۰ which according to Google translates to 22.07.1402, 15:30.

The IntlDateFormatter class