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.
Join the DZone community and get the full member experience.Join For Free
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:
To parse a date time string:
For validating a date, we will use the
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.
Published at DZone with permission of Swathi Prasad , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.