Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JavaScript’s Dates Are Fun With Moment.js

DZone's Guide to

JavaScript’s Dates Are Fun With Moment.js

Manipulating dates in web applications is tricky, especially if your users travel across timezones. Learn how to use an open source framework to resolve this.

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

Date manipulation is incredibly common in most applications. It is one of those development hurdles that we all must deal with 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 the following line of code:

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

To parse a date time string:

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

For validating a date, we will 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. For example:

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

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

Note that the parser ignores non-alphanumeric characters, so both the lines above 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 on CodePen.

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.

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.

Topics:
javascript ,moment.js ,web dev

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}