Skip to content
Advertisement

How to get difference in dates between to dates in JavaScript

I have a split string lines=”Ram Hue, 134, 20.5.1994, 20.4.2004″ and I want to get the difference in dates between to dates 20.5.1994 and 20.5.1994, I tried in JavScript but i’ts not working. Also when trying to extract both dates using lines[2] lines[3] I’m getting wrong outputs

var date1 = new Date(lines[2])
var date2 = new Date(lines[3])
var diffDays = parseInt((date2-date1)/(1000*60*60*24),10)
console.log(diffDays)

Advertisement

Answer

Since lines is a string, lines[2] will just get you the character with index 2 within the string. Instead you need to split the string before:

const arr = lines.split(',');

Then you can access both date strings as arr[2] and arr[3]

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement