Explain Codes LogoExplain Codes Logo

How to convert Gregorian date to Persian date in JavaScript?

javascript
date-conversion
persian-date
intl-datetimeformat
Anton ShumikhinbyAnton Shumikhin·Oct 28, 2024
TLDR

The Intl.DateTimeFormat with 'fa-IR' locale and calendar: 'persian' gives a succinct solution for date conversion:

let persianDate = new Intl.DateTimeFormat('fa-IR', { calendar: 'persian' }).format(new Date()); console.log(persianDate); // You're now Persia-nating the date!

**Focus: ** The Internationalization API is the key to easy conversion.

Housing up a date

Need to display a date with more granularity? Decimalize it using these formatting options:

let options = { year: 'numeric', month: 'long', day: 'numeric' }; let persianDate = new Intl.DateTimeFormat('fa-IR-u-nu-latn', options).format(new Date()); console.log(persianDate); /* Now, that's Persian precision! */

Get Latin in the mix

To artistically sneak in Latin digits within the Persian date string, use the 'fa-IR-u-nu-latn' language tag:

let persianDate = new Intl.DateTimeFormat('fa-IR-u-nu-latn').format(new Date()); console.log(persianDate); // Latin-ing in Persian territories!

Should I use JavaScript date libraries?

Navigation of date and time in JavaScript can be like a cat herding a group of squirrels. Fret not! JavaScript libraries like jalali-moment and jalaali-js can come to the rescue:

const moment = require('jalali-moment'); let persianDate = moment(new Date()).locale('fa').format('YYYY/MM/DD'); console.log(persianDate); /* Whoa, when did we time-travel to Persia? */

Leaping over calendar differentials

When calendars compete on leap years and formats, some manual tweaking might be required. Brush up on your Jalali vs Gregorian trivia!

To make your code Persian-proof

Just converting dates is like applying band-aid on a broken fence. Let's mend it:

Edge-case Handling:

  • Use a 360° view: Account for calendrical peculiarities, such as Persian leap years.
  • Time zoned-out much? Remember, timezone differences can subtly distort conversions.
  • Cross out the cross-locale mess: Regional settings may have their own date folklore.

Library Showdown:

  • jalali-moment pulls the strings with moment.js, diverse formats, and swifter time handling.
  • jalaali-js is your featherweight friend for simple conversions.

Features, not bugs:

Your users deserve dates served in their cultural platter. Humanize your dates; make weeks and months native.

Code maintainability and you

Nurse your code to health with these tips:

  • Simplicity: Keep your code DRY with the built-in JavaScript functions.
  • Keep pace: Stay updated with the frenetic race of web standards and ECMA updates.
  • Doc blocker: Drape your code in comments; you're writing for humans.
  • Test like tomorrow: Test for cross-device support and edge-case performance.