You can bring in Moment.js into your project depending on where you are running your code:
- If you are running your code with Node.js, you can install it with NPM by running npm install --save moment and then requiring it into your file like so: const moment = require('moment'); (see docs for the moment NPM package)
- If you are running your code with a web browser, you can download the Moment.js library from their website and include it in your HTML document with a script tag like so: <script src="/path/to/moment.js"></script>.
Let’s go over some examples of the most common operations I generally use Moment.js for:
Parsing and Formatting
Let’s say that you are given a bunch of objects with timestamps in a non-standard format, something like “29–03–1989”. Let’s also say that we want to display this in a more user friendly format, something like “day of the week, but just the first three letters, then the month, then the date with its corresponding ordinal, a comma and the year”. Moment.js allows us to parse and format dates on the fly by using format strings:
Those weird strings with all the Ds, Ms and Ys are format strings and once you get used to the syntax, they allow you to go from any format to any other format with the change of a simple string argument. Extremely useful if you have an indecisive client! You can find more about parsing and format dates on this page of the Moment.js documentation.
Any application that needs some sort of scheduling could greatly benefit from the date manipulation methods Moment.js offers:
- We can add or subtract any unit of time
- We can calculate dates to the start or end of any unit of time
- We can even offset dates according to UTC/GMT (e.g. Japan is on GMT+9)
Displaying Relative Times
Sometimes you want to show your users something happening relative to the time they’re reading it. Let’s say your user is getting a package delivered and you want to show them how much they have to wait:
The great benefit of these methods is how readable they are. Writing code that is easy to understand leads to fewer bugs and, in case of bugs, easier debugging.
If you are already working on a project with dates, have a go at refactoring some of your code to use Moment.js. Using the Test Driven Development skills we teach on our courses it should be a breeze!
A Beginner's Guide to Test-Driven Development
Test Driven Development (TDD) is an industry best practice, and it's a method we teach our students from week 1 of the course.
Head of Software Development