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.
To parse a date time string, we can just do as follows:
To check if your date was parsed and valid, use the isValid() method:
If you know the format of an input string, we can use that to parse a date.
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.