Last active
July 17, 2020 05:18
-
-
Save harshithjv/1defcf3a4177e3b40204dfd73239b71b to your computer and use it in GitHub Desktop.
Retrieve Formatted items individual items of Date in JavaScript. (ECMAScript Internationalization API (ECMA-402))
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Reference for Locale String options: https://tc39.es/ecma402/#sec-datetimeformat-abstracts | |
| // MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString, | |
| // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat | |
| // ISO or JSON date string conversion | |
| var d = new Date('2020-07-17T05:01:16.759Z') | |
| // partial ISO string also allowed | |
| var d1 = new Date('2020-07-17T05:01') | |
| // Locale String conversion with options specified in ECMA-402 standard API | |
| let options = { year: 'numeric', month: 'short', day: '2-digit' }; | |
| console.log(d1.toLocaleString('default', options)); | |
| // Output: Jul 17, 2020 | |
| // use language code instead of default | |
| console.log(d1.toLocaleString('en-IN', options)); | |
| // Output: 17-Jul-2020 | |
| // use Intl.DateTimeFormat for I18N. Similar to specifying language in locale string | |
| console.log(new Intl.DateTimeFormat('en-IN', options).format(d1)); | |
| // Output: 17-Jul-2020 | |
| // Change month option from 'short' to 'narrow' that will give just initials instead of 3-char representation of month. | |
| options.month = "narrow"; | |
| console.log(new Intl.DateTimeFormat('en-IN', options).format(d1)); | |
| // Output: 17-J-2020 | |
| // Note: Same output if '.toLocaleString()' is used. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment