Skip to content

Instantly share code, notes, and snippets.

@unicornist
Last active May 3, 2024 14:15
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save unicornist/0e37b3691551c42c716e96c125b99df7 to your computer and use it in GitHub Desktop.
Save unicornist/0e37b3691551c42c716e96c125b99df7 to your computer and use it in GitHub Desktop.
Natively Format Javascript Dates & Numbers in different Locales (Including Persian Calendar)
(12345.6789).toLocaleString("fa-IR"); // ۱۲٬۳۴۵٫۶۷۹
var now = new Date();
now.toLocaleString(); // 1/27/2018, 12:07:03 AM
now.toLocaleDateString(); // 1/27/2018
now.toLocaleTimeString(); // 12:07:03 AM
now.toLocaleString("fa-IR") // ۱۳۹۶/۱۱/۷،‏ ۰:۰۷:۰۳
now.toLocaleDateString("fa-IR") // ۱۳۹۶/۱۱/۷
now.toLocaleTimeString("fa-IR") // ۰:۰۷:۰۳
var formatOptions = {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'};
now.toLocaleString("en-US", formatOptions); // "Saturday, January 27, 2018"
now.toLocaleDateString("fa-IR", formatOptions); //۱۳۹۶ بهمن ۷, شنبه
/*
Syntax
toLocale...([locale [, options]]);
Locale
String or Array of Strings of locale code (language-COUNTRY) & two extra options for Numbering system & Calendar selection as below:
"nu": "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt"
"ca": "gregory", "persian", "islamic", "islamicc", "iso8601", "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "hebrew", "indian", "japanese", "roc"
Options
Object with following params:
"weekday": "narrow", "short", "long", locale-specific by default
"month": "numeric", "2-digit", "narrow", "short", "long", locale-specific by default
"year", "day", "hour", "minute", "second": "numeric", "2-digit", locale-specific by default
"hour12": true, false, locale-specific by default
"timeZoneName": "short", "long", locale-specific by default
"localeMatcher": "lookup", "best fit" (default)
"formatMatcher": "basic", "best fit" (default)
Option Subsets
weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute
*/
@kamranzre
Copy link

hi how change digit this ۱۳۹۶/۱۱/۷ to 1396/11/7

@unicornist
Copy link
Author

hi how change digit this ۱۳۹۶/۱۱/۷ to 1396/11/7

Looking at the documentation (which I tried to describe like a cheatsheet in comments) you can pass options, and your usecase could be generated like:

now.toLocaleDateString('fa-IR', {numberingSystem: 'latn'})

@SolgiDeveloper
Copy link

SolgiDeveloper commented Jun 17, 2023

you can use this for your purpose
now.toLocaleDateString("fa-IR-u-nu-latn")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment