Skip to content

0xhjohnson

Display Previous Months using Javascript

Javascript, Moment.js1 min read

Traversing my thought process and solution to displaying the current and previous X months in JS. Common use case being for a months dropdown.

We know that a function is going to be needed that accepts arguments of some sort. I decided upon using numMonths (the number of previous months we would like) and includeCurrMonth (whether or not to include the current month). While handling some basic type checking and error handling.

Lets use the includeCurrMonth argument to set whether we would like to start at current month or previous month. Once the start position is set when can start subtracting months. The moment.js library makes this easy via the subtract manipulation function.