4

Given a date such as November 23, 2021 in this European format: 23/11/2021. I try converting it to a date object like this:

const dateString =  '23/11/2021'
const dateObj = new Date(dateString)

However, this is giving me an error saying this is an invalid date. I don't want to just convert it to the US date format, since I am trying to see if I can sort the dates given the European format. Anyone know how I can convert this to a date object given the european date format?

smolkitty
  • 109
  • 1
  • 6

1 Answers1

1

If the format is always dd.MM.yyyy it can be done by slicing the date string to get the year, month and day required to create the Date object.

const date =  '23/11/2021'

const d = date.slice(0,2),
      m = date.slice(3,5),
      y = date.slice(6,10);

const dateObj = new Date(y, m, d)

console.log(dateObj)
Gass
  • 7,536
  • 3
  • 37
  • 41