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

前端 未结 16 2550
北海茫月
北海茫月 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:56

    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)

提交回复
热议问题