I have a date in a string format that looks like so:
"31/07/2022 16:00"
… and I want to change it to a valid Javascript date and time.
I’ve tried changing the forward slashes to '-'
with this code:
let lala let lalawood = '31/07/2022 16:00' lala = lalawood.replace(///g, '-'); console.log(lala); // outputs 31-07-2022 16:00
but it returns '31-07-2022 16:00'
which is still an invalid date time.
How can I convert this into a valid Date and Time so that I can use it to compare two dates programmatically?
Advertisement
Answer
The problem here is that you are using time in European format (DD/MM/YYYY), while JavaScript compiling it as American time format (MM/DD/YYYY), Here is a snippet that switch days and months to create a valid date
let s = '31/07/2022 17:30'; s = s.replace(/[^0-9 ]/g, " ").split(' '); let d = new Date(s[2], s[1]-1, s[0], s[3], s[4]); console.log(d);