Why are Dates Important?
Dates are important because they provide a way to measure time. Time is a vital part of almost every appplication we develop whether it’s a simple To-Do list or a complex financial application. Knowing how to set dates correctly ensures that our applciations function as intended and provides a consistent user experience.
How to Set Dates
Make use of a popular open-source library that makes working with dates and times much easier. We recommend using Moment.js whenever possible as it provides a more concise API and avoids some of the pitfalls associated with the Date object (e.g. different implementations in different browsers).
When setting a date, there are four properties that we need to be aware of: year, month, day, and hour.
- The year can be represented by either four digits (YYYY) or two digits (YY).
- The month can be represented by either its full name (January – December) or by a number between 1 – 12 inclusive.
- The day should always be represented by two digits ranging from 01 – 31 inclusive regardless of the month selected.
- Finally, the hour can be represented using either a 24 hour clock (00 – 23) or am/pm notation (12:00am – 11:59pm).
Practical Usage Scenarios
- One common scenario is calculating the number of days until a particular event such as Christmas or a birthday party.
- Another practical usage scenario for dates is displaying them in specific formats such as “Monday, January 1st” or “1/1/2019″/”
- Use Moment.js instead of the built-in Date object whenever possible
- When setting hours always use 24 hour notation (00 – 23)
- When setting years always use four digits (YYYY) as two digit years can cause ambiguity
- Always test your code thoroughly! Incorrectly formatted dates can cause unexpected results
- Use comments liberally to annotate your code so that others (and future you!) know what’s going on
- Have fun! Programming should be enjoyable so make sure you take breaks and come back refreshed.