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.
- String: This is the date string to be parsed.
- String[]: It is the array of strings that specifies all the formats that have to be parsed.
- String: It is the locale to be parsed by the method.
- Boolean: It specifies whether strict parsing would be used for the parsing.
Return Value: This function returns the parsed Moment object.
Formatting Preference:
- It prefers valid dates over invalid ones.
- It prefers formats earlier in the array than later.
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”.
Javascript
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”.
Javascript
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/
Contact Us