0

I have two dates in YYYY-MM-DD format. I want to subtract the dates and get the integer value of two numbers between them.

If I have:

var startDate = "2014-09-25";
var endDate = "2014-10-12";

I would want the difference to be 18 days. I was planning on putting it in my Google Analytics, so it could look like this:

query: {
    ...
    start-date: "18daysAgo",
    end-date: "today"
}

How would I go about this?

Graham S.
  • 163
  • 2
  • 9

1 Answers1

1

This is how you can do it:

var aDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var date1 = new Date(2014, 09, 25);
var date2 = new Date(2014, 10, 12);

var diffDays = Math.round(Math.abs((date1.getTime() - date2.getTime())/(aDay)));

window.alert("" + diffDays);

This will give you the number of days between 2 dates.

brso05
  • 13,142
  • 2
  • 21
  • 40
  • 1
    Tried this. I keep getting `1` as my answer for the dates `2014-10-12` and `2014-09-30` (Those are the dates I'm testing right now.) – Graham S. Oct 21 '14 at 21:03
  • i deleted the comment harping on your typo, and the one about the time of day. i realized that since you are always producing a local midnight date by being unspecific about timezones, it should balance out, which is not the case if you were parsing dates. crude write-up and over-zealous commenting aside, it's not a bad answer... oh, and i promise you can subtract dates, that's one you need to try ;) – dandavis Oct 21 '14 at 21:24
  • @dandavis I know you can subtract dates but it won't give him the answer he is looking for (number of days between 2 dates) that was what I meant when I said it wouldn't work. It's alright though no hard feelings I will delete my other comments so there is not as much overhead with this answer. I should have worded my comments a little differently I was just frustrated because you were saying this doesn't work when it does and it is a solution to his problem without using external libraries (maybe try the solution before saying it doesn't work). – brso05 Oct 22 '14 at 12:34
  • @dandavis That being said I shouldn't have made some of the comments I did. – brso05 Oct 22 '14 at 12:35