Every so often a project comes up that requires the use of dates in the web interface – event listings, custom calendar outputs and similar uses. It is on these projects that I am reminded of the pitfalls of working with date objects in JavaScript. Something I have known for years but forget when not working with it regularly is the mixture of 0 based and 1 based arrays that compose the parts of a date object.

The Date and the Year parts are stored as 1 based numbers, but when working with the day of the week, the month and any of the time parts, they are all 0 based. While this means we have to remember to be careful when creating and displaying the month or the day of the week, it makes for a common and easy pattern of using arrays to display a more verbose string representing the value. First we create simple arrays to store these values like these:

Then once we have these arrays stored somewhere in our script we can use the getDate() or getMonth() methods to easily get the value without having to do any date manipulations.

This is not all that groundbreaking or new but it is something that can come in handy. If we combine it with one more array for the days of the month we can create a simple function that can create the verbose date format that most people prefer without any extra JavaScript libraries or complex logic (example – Monday, December 29th, 2014).


Like this post? Share it!