0

Its so surprising to see JavaScript not having a easy to use format for dates.

I'm trying do get this format (example in python)

>>> datetime.now().strftime("%Y%m%d")
'20221228'

I did find that Intl.DateTimeFormat can do some format the Date() objects. But from the docs I don't see how to make a custom format out of this.

There are canned formats en-US en-GB which it would be nice to define a format.

> var dateOptions = {year:'numeric', month:'numeric', day:'numeric'}
> console.log( Intl.DateTimeFormat('en-GB', dateOptions).format(Date.now()))

28/12/2022

> console.log( Intl.DateTimeFormat('en-US', dateOptions).format(Date.now()))

12/28/2022

It partially controls formatting but does anyone know how to actually control the output format with Intl.DateTimeFormat to output YYYYMMDD?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Peter Moore
  • 1,632
  • 1
  • 17
  • 31
  • Briefly, use `formatToParts` and combine the parts as you want. – Heretic Monkey Dec 28 '22 at 17:42
  • @HereticMonkey LOL that `formatToParts` is very lame solution but ill take it. To have DateTimeFormat without an actual way to format dates seems very broken. – Peter Moore Dec 28 '22 at 18:18
  • Have you looked into how people format dates across the world? There's not just MM/DD/YYYY, DD/MM/YYYY, and YYYYMMDD; there are eras, emperor reigns, different calendars, etc.. ECMA wisely offloaded a lot of that to other organizations. Way too much of a hassle. – Heretic Monkey Dec 29 '22 at 01:49

1 Answers1

0

Based upon @HereticMonkey here is what I hacked to solve it with the core JavaScript. Cant imagine why Intl.DateTimeFormat is not capable of user defined formatting. This is basic needs.

function toYYYYMMDD(date){
    let dateFields = {}
    let options = {
        year: 'numeric',
        month: 'numeric',
        day: 'numeric'
    }
    let formatDate = new Intl.DateTimeFormat('en-US', options )
    formatDate.format(date)
    let parts = formatDate.formatToParts()

    for (var i = 0; i < parts.length; i++) {
        dateFields[parts[i].type] = parts[i].value;
    }
    return dateFields.year + dateFields.month + dateFields.day
}

toYYYYMMDD(new Date())
'20221228'

EDIT this way is also lame because it cant convert time to localtime and its way too much code.

i finally went with luxon which is way easy.

luxon.DateTime.local(2022, 12, 28, 08, 00, 00).toFormat("yyyyMMdd")
"20221228" 

luxon.DateTime.local(2022, 12, 28, 18, 00, 00).toFormat("[yyyyMMMdd] HH:mm")
"[2022Dec28] 18:00" 

And time 24 or 12 hour

luxon.DateTime.local(2022, 12, 28, 18, 00, 00).toFormat("hh:mm a")
"06:00 PM"
luxon.DateTime.local(2022, 12, 28, 18, 00, 00).toFormat("HH:mm")
"18:00" 
Peter Moore
  • 1,632
  • 1
  • 17
  • 31