Open In App

Moment.js Parsing String + Format

Moment.js Parsing String+Format is used when we want to parse a date string through the given format string. The parser will ignore the non-alphanumeric characters of the format. It returns the parsed date as a Moment object.

Syntax:



moment(String, String, Boolean);

Parameters: This method accepts three parameters as mentioned above and described below:

Return Value: This function returns the parsed date as a Moment object.



Note: This will not work in the normal Node.js program because it requires the moment.js library to be installed.

Moment.js can be installed using the following command:

npm install moment

Example 1: Getting the date as output.




const moment = require("moment");
 
let date = moment("01-11-2022", "MM-DD-YYYY");
console.log("The date is", date);

Output:

The date is Moment<2022-01-11T00:00:00+05:53>

Example 2: The parser ignores non-alphanumeric characters by default.




const moment = require("moment");
 
let date = moment("2022/12/01", "YYYY-MM-DD");
console.log("The date is", date);

Output:

The date is Moment<2022-12-01T00:00:00+05:30>

Reference: https://momentjs.com/docs/#/parsing/string-format/

Article Tags :