-2

I'm trying to create a date with the format 'mmddyyyy'. I've noticed I can pass a four digit string, but when I use the format above, it says invalid date. How can I go about this with pure js?

let dateString = '01012022'
let d = new Date(dateString)
usr4896260
  • 1,427
  • 3
  • 27
  • 50
  • 1
    maybe a duplicate of https://stackoverflow.com/a/33299764/7133482 – Sayuri Mizuguchi May 09 '22 at 14:36
  • 2
    Using this type of date formats in software is strongly recommended to avoid! Please think if you really need it or if there is any change to replace it by ISO standard. – Thallius May 09 '22 at 14:37
  • How would `Date` function know if you are passing timestamp or a date when you are passing just numbers? you need split it into separate day/month/year – vanowm May 09 '22 at 14:38
  • @Thallius I agree! I'm working with legacy software and unfortunately unable to change it. – usr4896260 May 09 '22 at 14:51

2 Answers2

3

maybe you want something like that

let dateString = '01012022'
let [match, dd, mm, yyyy] = dateString.match(/(\d{2})(\d{2})(\d{4})/)
// iso format
let d = new Date(`${yyyy}${mm}${dd}`)
Pierre
  • 432
  • 1
  • 7
0

Seems like you have to split your string into pieces then use common Date() constructor with separated day, month and year

//Your string with date
let dateString = '01012022';
//extracting 2 first numbers as m (month), 2 second as d (day) and the last 4 as y (year)
let {d,m,y} = /(?<m>\d{2})(?<d>\d{2})(?<y>\d{4})/.exec(dateString).groups;
//then create new date using constructor
let date = new Date(y,m,d);
Jaood_xD
  • 808
  • 2
  • 4
  • 16