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.
Share
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.
This should just work
EDIT: Fixed bug pointed by @bdukes
EDIT:
For an explanation of the behavior,
oldBegin,oldEnd, andnewBeginareDateinstances. Calling operators+and-will trigger Javascript auto casting and will automatically call thevalueOf()prototype method of those objects. It happens that thevalueOf()method is implemented in theDateobject as a call togetTime().So basically:
date.getTime() === date.valueOf() === (0 + date) === (+date)