简体   繁体   中英

Get difference of two dates in JavaScript

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM