Open In App

Moment.js Parsing String + Formats

Moment.js Parsing String + Formats is used when we are not sure of the exact format of an input date string. However, we can specify the possible formats in an array as a parameter for it to try and match. It is the same as String + Format, with the exception that this supports multiple formats.

As it takes more time for parsing each of the formats, it is recommended to use a lesser number of formats or use a single format.



Syntax:

moment(String, String[], String, Boolean);

Parameters: This method accepts four parameters.



Return Value: This function returns the parsed Moment object.

Formatting Preference:

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: Here, the input will be matched with the format “MM-DD-YYYY”.




const moment = require("moment");
  
// Match the date with the given formats
let date = moment(moment(
    "11-29-2022",
    ["MM-DD-YYYY", "DD-MM-YYYY"])
);
console.log("The date is", date);

Output:

The date is Moment<2022-11-29T00:00:00+05:30>

Example 2: Here, the input will be matched with the format “YYYY-MM-DD”.




const moment = require("moment");
  
// Match the date with the given formats
let date = moment(moment(
    "2022-10-25",
    ["MM-DD-YYYY", "YYYY-MM-DD"])
);
console.log("The date is", date);

Output:

The date is Moment<2022-10-25T00:00:00+05:30>

References: https://momentjs.com/docs/#/parsing/string-formats/


Article Tags :