Notes

Formatting dates in JavaScript

Edit on GitHub

JavaScript
2 minutes
1dateObj.toLocaleTimeString([locales[, options]])
  • Locales (string/array of strings, optional) en-US, en-GB, ar-EG etc.
  • Options (object, optional) where you can specify properties and their values, e.g. timeZone: 'Asia/Karachi'

Formatting locale strings

 1// Locale Strings
 2let date = new Date()
 3console.info('en-us', date.toLocaleString('en-us')) // "1/10/2017, 3:29:15 PM"
 4console.info('en-GB', date.toLocaleString('en-GB')) // "10/01/2017, 15:29:15"
 5console.info('ar-EG', date.toLocaleString('ar-EG')) // "١٠‏/١‏/٢٠١٧ ٣:٣٢:٣٣ م"
 6console.info('de-DE', date.toLocaleString('de-DE')) // "10.1.2017, 15:32:33"
 7
 8const locale = navigator.language || navigator.userLangauge // find out the browser's locale
 9
10let localeStringFormat = {
11  weekday: 'long',
12  month: 'long',
13  day: 'numeric',
14  year: 'numeric'
15}
16console.info('month', date.toLocaleString(locale, {month: 'long'})) // "January"
17console.info('en-us', date.toLocaleString('en-us', localeStringFormat)) // "Tuesday, January 10, 2017"
18console.info('en-GB', date.toLocaleString('en-GB', localeStringFormat)) // "Tuesday, 10 January 2017"
19console.info('ar-EG', date.toLocaleString('ar-EG', localeStringFormat)) // "الثلاثاء، ١٠ يناير، ٢٠١٧"
20console.info('de-DE', date.toLocaleString('de-DE', localeStringFormat)) // "Dienstag, 10. Januar 2017"

Validating and formatting dates

 1const UNIX = '1481884441'
 2const ISO8601 = '2016-11-04T17:39:59.910Z'
 3const time = new Date(ISO8601)
 4const locale = 'en-US'
 5/* Locales
 6* en-US: November 4, 2016, 22:39
 7* en-GB: 4 November 2016, 10:39 PM
 8*/
 9
10
11// Format using Moment.js
12const formattedUnix = moment.unix(UNIX).format('MMM D, YYYY, HH:mm')
13const formattedISO = moment(ISO8601).format('MMM D, YYYY, HH:mm')
14console.info('formatted Unix:', formattedUnix) // "Dec 16, 2016, 15:34"
15console.info('formatted ISO:', formattedISO) // "Nov 4, 2016, 22:39"
16
17
18// Format using Date methods
19let date = time.getDate()
20let month = time.toLocaleString(locale, {month: 'short'})
21let year = time.getFullYear()
22let hours = time.getHours()
23let mins = time.getMinutes()
24
25console.info(`${month} ${date}, ${year}, ${hours}:${mins}`) // "Nov 4, 2016, 22:39"
26
27
28// Format using Locale string
29const dateStringFormat = {
30  month: 'short',
31  day: 'numeric',
32  year: 'numeric',
33  hour: 'numeric',
34  minute: 'numeric'
35}
36console.info('locale string', time.toLocaleString(locale, dateStringFormat)) // "Nov 4, 2016, 10:39 PM"