There is no build in "one function do it all" to get your outcome right away.
Option 1:
However you can use the provided functions getFullYear
, getMonth
and getDate
to get to your result:
let d = new Date()
let formatted = d.getFullYear().toString().slice(2,4) +
(d.getMonth()+1 > 10 ? d.getMonth()+1 : `0${d.getMonth()+1}`) +
(d.getDate() > 10 ? d.getDate() : `0${d.getDate()}`)-0
Lets get through it line by line
// Uses the getFullYear function which will return 2019, ...
d.getFullYear().toString().slice(2,4) // "19"
// getMonth returns 0-11 so we have to add one month,
// since you want the leading zero we need to also
// check for the length before adding it to the string
(d.getMonth()+1 < 10 ? d.getMonth()+1 : `0${d.getMonth()+1}`) // "03"
// uses getDate as it returns the date number; getDay would
// result in a the index of the weekday
(d.getDate() < 10 ? d.getDate() : `0${d.getDate()}`) // "22"
// will magically convert the string "190322" into an integer 190322
-0
Might be worth saying that this is a quick "how to achieve" it without installing any npm package but make sure to cover edge cases yourself as there are many when it comes to dates.
Option 2:
Another option would be to go for the toISOString
and use split, a bit of regex, and slice to receive your outcome:
d.toISOString().split('T')[0].replace(/\-/g, '').slice(2,8)-0
Again step by step with the output:
d.toISOString() // "2019-03-22T22:13:12.975Z"
d.toISOString().split('T') // (2) ["2019-03-22", "22:13:12.975Z"]
d.toISOString().split('T')[0] // "2019-03-22"
d.toISOString().split('T')[0].replace(/\-/g, '') // "20190322"
d.toISOString().split('T')[0].replace(/\-/g, '').slice(2,8) // "190322"
d.toISOString().split('T')[0].replace(/\-/g, '').slice(2,8)-0 // 190322