Wednesday 14 November 2012

Date math

This short post forms part of our series explaining how the Snippets Bakery developed a new online order form with snazzy order confirmation emails which accurately handles date input. Today we're using those dates so it helps that we've recorded them in a helpful format!

If you've come from VBA then you'll be used to being able to add and subtract dates. In Excel, dates are stored as serial numbers equating to the number of days since 0-Jan-1900 (actually one greater than this number due to a deliberately continued bug in Lotus 123) with time as a decimal portion of a day.

In JavaScript, times are stored as the number of milliseconds since midnight 1-Jan-1970. What does that mean for us if we want to calculate the numbers of days between two dates? Well, firstly we need to get to the milliseconds (quickly achieved with getTime) and then we can subtract the smaller value from the larger - in this case we  are asking users to input a date in the future so we subtract the submission timestamp from this. Then we have with a bunch of milliseconds on our hands so we divide this number by 86,400,000 (the number of milliseconds in a day) and we are left with a number of days. In all likelihood this will be a fraction so I have rounded it down with a Math.floor function.


No comments:

Post a Comment