Search code examples
javascriptdate

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


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. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.


Solution

  • In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the getTime() method or just using the date in a numeric expression.

    So to get the difference, just subtract the two dates.

    To create a new date based on the difference, just pass the number of milliseconds in the constructor.

    var oldBegin = ...
    var oldEnd = ...
    var newBegin = ...
    
    var newEnd = new Date(newBegin + oldEnd - oldBegin);
    

    This should just work

    EDIT: Fixed bug pointed by @bdukes

    EDIT:

    For an explanation of the behavior, oldBegin, oldEnd, and newBegin are Date instances. Calling operators + and - will trigger Javascript auto casting and will automatically call the valueOf() prototype method of those objects. It happens that the valueOf() method is implemented in the Date object as a call to getTime().

    So basically: date.getTime() === date.valueOf() === (0 + date) === (+date)