JavaScript’s Dates are fun with Moment.js

Date manipulation is incredibly common in most of the applications. It is one of those development hurdles that we all must deal at some point in our career. We have several tools for manipulating dates in JavaScript. Moment.js is one of those tools for JavaScript development.

It makes dates and times easy to format, parse, validate and internationalize. The standard JavaScript Date object isn’t too bad; it just requires writing a lot of code to do complex parsing, validation and displaying of dates.

To begin with, link the library from cdnjs in your HTML. If you are using NodeJs, you can do “npm install moment –save”. Let’s look at some examples to get a glimpse of Moment.js.

Parsing and Validating Dates

To get a current date, just add a following line of code.

moment().format('YYYY-MM-DD');

To parse a date time string, we can just do as follows:

moment('2017-04-20 09:30:26.123');

To check if your date was parsed and valid, use the isValid() method:

moment('2017-04-20 09:30:26.123').isValid();

>> true

moment('123456').isValid();

>> false

If you know the format of an input string, we can use that to parse a date.

moment("04-21-2017", "MM-DD-YYYY");

moment("04/21/2017", "MM-DD-YYYY");

Note that the parser ignores non-alphanumeric characters, so both will return the same result.

Specifying Multiple Formats

Suppose you don’t know the format of the input string, then Moment lets you provide an array of formats.

Let’s look at an example:

moment("04-21-2017", ["MM-DD-YYYY", "YYYY-MM-DD"]); // Uses the first format.

In the example above, it tries to match the input with the specified array of formats.

Check out the demo for this article here.

Conclusion

Moment.js is a great library to have if you are often working on dates in JavaScript. We have covered just some basics in this article. It has plenty of other cool features to offer. Check out their documentation and source code on GitHub.

One thought on “JavaScript’s Dates are fun with Moment.js

Comments are closed.