JavaScript Data Structures - A TimeInterval Object |
Written by Ian Elliot | ||||
Thursday, 16 April 2020 | ||||
Page 3 of 3
Trying it out and extending DateNow you can try it out. For example: var t= TimeInterval(1,0,0); This creates a TimeInterval of 1 hour and then adds 1 day 1 hour and 2 seconds to it. The display shows: 1 Day(s) 2:2:0:0 Now we have one final problem. You can do time interval arithmetic with the TimeInterval object but you often want to add a TimeInterval object to a Date object. You can already add a Date object to a TimeInterval object, but the problem is that the result is a TimeInterval object - which is usually not what you want. So the temptation is to give the existing Date object an add method of its own which accepts either a Date or a TimeInterval object. You can do this quite easily using the Prototype property but it is better not to. If you start extending built-in objects, then things can become confusing and any frameworks you are using might behave strangely. A much better option is to add a new object based on the built-in object and then customize it by augmentation. In this case, for example, let's create a Date2 object, complete with an add method: var Date2 = function(){ Now you can write things like: var d = Date2(); to add 1 hour to the current date/time. This looks good, but there is a problem. The Date object has a range of different ways it can be called with varying numbers of parameters. Our example only uses a default constructor for today's date/time. One solution is to use apply(this,arguments) but, while this works with other objects, it doesn't work with Date. The reason is that it is implemented in an idiosyncratic way. If you call Date without new in front of it then it always returns a formatted string for the date and never a Date object. This means you can not use apply to create a Date object. The only solution in this case is to work through the possibilities, which is easy but tedious: Date2 = function(){ Now you can construct a Date2 object in exactly the same way as a Date object. (If you know a better way of doing this email me.) From here you can add other methods and generally extend the Date2 object to work with the TimeInterval object. Further readingSpeed dating - the art of the JavaScript Date object Date Hacks - Doing JavaScript Date Calculations
|
||||
Last Updated ( Saturday, 25 April 2020 ) |