-3

I have 2 dates stored like this:

"04.12.2019, 09:35" // Today
"05.12.2019, 12:50" // Some different date

And i want to compare them (wether the date has already passed or still will come).

My thought about this was converting them to a Date and then comparing the dates but the online solutions to converting these strings into a date all use moment.js

Is there a way to convert these strings to a date without using moment.js or comparing them without even converting them to a date at all?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
niehoelzz
  • 385
  • 5
  • 20

3 Answers3

0

You can just use Date i guess :

let dateString = '04.12.2019, 09:35'.replace(/\./g,' ').replace(',', '');
let dateString2 = '05.12.2019, 12:50'.replace(/\./g,' ').replace(',', '');
let newDate = new Date(dateString);
let newDate2 = new Date(dateString2);
//Your comparison between newDate and newDate2 here
KBell
  • 502
  • 8
  • 23
  • When i do this: let A = new Date("04.12.2019, 09:35"); console.log(A); I just get the log: "Invalid Date" – niehoelzz Dec 04 '19 at 08:49
  • @niehoelzz you need to replace dots with spaces. I'll update my answer. – KBell Dec 04 '19 at 09:04
  • @niehoelzz this should work now. Ah you already solved it :) – KBell Dec 04 '19 at 09:11
  • Now i got another problem, since im in germany, we write our dates like this: DD MM JJJJ but Date takes the args like the follwing: MM DD JJJJ. Is there a way to set properties to the "new Date()"? – niehoelzz Dec 04 '19 at 09:25
  • @niehoelzz Not that i know, you can invert month and day by string manipulation (using `dateString.split(' ')`) – KBell Dec 04 '19 at 09:43
0

You can do like this:

let A = new Date("04.12.2019, 09:35");
let B = new Date("05.12.2019, 12:50");

if (A === B) { // Do Stuffs }
0

JavaScript Date instance

let date1 = new Date("04.12.2019, 09:35");
let date2 =  new Date("05.12.2019, 12:50");

let result = date1 < date2 ? 'still will come' : 'already passed'; 
console.log(result);
Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20