In the Formatting JavaScript Date Intervals into Years, Months, Weeks, and Days article, I described how to break down JavaScript date intervals into various units using the momentJS library. You might wonder what practical applications that this exercise might have in “real life”. There are many, but one common usage is to include them within countdown calculators, for instance, how many days remain until next Christmas. In today’s tutorial, we’ll construct an HTML5 form that provides detailed information about a person’s age and birthdays based on their date of birth. In follow-up installments, we’ll exploit momentJS’s many features to effectuate the various calculations required.
Why MomentJS?
In the Formatting JavaScript Date Intervals into Years, Months, Weeks, and Days article, I warned that calculating months and years between two dates is fraught with challenges due to the variability of month lengths and leap years. That’s why I always recommend using a well-known JS (JavaScript) date library for client-side calculation of date intervals. I personally rely on momentJS for such tasks. It’s both easy to use and yields highly accurate results.
The HTML Code
Whereas the Formatting JavaScript Date Intervals into Years, Months, Weeks, and Days demo employed the HTML5 date input type for data entry purposes, our Birthday Countdown form will use three separate number inputs for each (day, month, and year) date part. Not to say that this is superior to the alternate approach, but separating each date part does make validation a little easier. I’ve also seen dropdowns employed for this purpose.
Calculated values are displayed within read-only inputs. These are rendered borderless with a light gray background using CSS to differentiate these from input fields.
Before we get into the minutiae of the markup, let’s take a look at the form without CSS or JS, just to see what types of calculations we’ll eventually have to perform:
On what day of the week were you born?
Please Enter your birthday
(then click the “Update”button)
To get a feel for the formatted output data, here are the results for top Canadian tennis pro Milos Raonic, who was born on December 27th, 1990: