How do I get the difference between two Dates in JavaScript?

前端 未结 16 2559
北海茫月
北海茫月 2020-11-22 03:03

I\'m creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date.

16条回答
  •  不要未来只要你来
    2020-11-22 03:50

    JavaScript perfectly supports date difference out of the box

    https://jsfiddle.net/b9chris/v5twbe3h/

    var msMinute = 60*1000, 
        msDay = 60*60*24*1000,
        a = new Date(2012, 2, 12, 23, 59, 59),
        b = new Date("2013 march 12");
    
    
    console.log(Math.floor((b - a) / msDay) + ' full days between'); // 364
    console.log(Math.floor(((b - a) % msDay) / msMinute) + ' full minutes between'); // 0
    

    Now some pitfalls. Try this:

    console.log(a - 10); // 1331614798990
    console.log(a + 10); // mixed string
    

    So if you have risk of adding a number and Date, convert Date to number directly.

    console.log(a.getTime() - 10); // 1331614798990
    console.log(a.getTime() + 10); // 1331614799010
    

    My fist example demonstrates the power of Date object but it actually appears to be a time bomb

提交回复
热议问题