smolkitty
smolkitty

Reputation: 149

How to convert european date format to Date Object in react native and/or javascript?

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?

Upvotes: 5

Views: 1611

Answers (1)

Gass
Gass

Reputation: 9344

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)

Upvotes: 3

Related Questions