I have a date in a string format that looks like so:
JavaScript
x
2
1
"31/07/2022 16:00"
2
… and I want to change it to a valid Javascript date and time.
I’ve tried changing the forward slashes to '-'
with this code:
JavaScript
1
5
1
let lala
2
let lalawood = '31/07/2022 16:00'
3
lala = lalawood.replace(///g, '-');
4
console.log(lala); // outputs 31-07-2022 16:00
5
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
JavaScript
1
5
1
let s = '31/07/2022 17:30';
2
s = s.replace(/[^0-9 ]/g, " ").split(' ');
3
let d = new Date(s[2], s[1]-1, s[0], s[3], s[4]);
4
console.log(d);
5