0

I am trying to write a date compare function to see if the stored Data is up to date with what i am trying to import. To do so i need to compare my stored Sales date with the Date provided in a csv file. My stored Sales Date is in a the following format 2007-03-06T00:00:00.000Z and the date in my csv is 05/10/2019 I know i can try to extrct date from the jsonString but i am hoping there is a function which will allow me to do a simple compare. Below is a simple slice i used to make it work but there should be a better way

date1 = "2019-05-10T00:00:00.000Z" 
date2 = "05/10/2019"

newDate = date1.slice(5,7) +"/" + date1.slice(8,10) +"/" + date1.slice(0,4)
console.log(newDate)

if (newDate != date2){
  console.log("dates dont match")
}
else {
  console.log("We have latest sale")
}
NoSoup4you
  • 640
  • 1
  • 10
  • 34
  • Convert the strings to dates with [Converting a string to a date in JavaScript](https://stackoverflow.com/q/5619202/215552) then compare with [Compare two dates with JavaScript](https://stackoverflow.com/q/492994/215552) – Heretic Monkey Apr 15 '20 at 20:57
  • Does this answer your question? [Compare two dates with JavaScript](https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – Heretic Monkey Apr 15 '20 at 21:03

3 Answers3

2

Convert into dates then compare on date string.

date1 = "2019-05-10T00:00:00.000Z" 
date2 = "05/10/2019"
const d1 = new Date(date1)
const d2 = new Date(date2)
d1.toLocaleDateString() == d2.toLocaleDateString()

zavr
  • 2,049
  • 2
  • 18
  • 28
0

What you are doing is comparing strings, not dates. You can use moment to convert strings to dates and compare date values

Nonik
  • 645
  • 4
  • 11
0

You need dates, but probably have to strip the time FOR date1 too for those of us that aren't in GMT:

date1 = "2019-05-10T00:00:00.000Z" 
date2 = "05/10/2019"
const d1 = new Date(date1.slice(5,7) +"/" + date1.slice(8,10) +"/" + date1.slice(0,4))
const d2 = new Date(date2)

if (d1.valueOf() != d2.valueOf()){
  console.log("dates dont match")
}
else {
  console.log("We have latest sale")
}
Ctznkane525
  • 7,297
  • 3
  • 16
  • 40