Open In App

Moment.js Parsing Special Formats

Last Updated : 20 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Moment.js is a JavaScript date library for parsing, validating, manipulating, and formatting dates. In this article, we will learn about the parsing of Special Formats in Moment.js. The ISO-8601 format is used as a standard for parsing the date and time. We can also specify HTML5 constants that can be specified in the HTML5_FMT property when parsing dates directly from the browser input elements.

Syntax:

moment(String, moment.CUSTOM_FORMAT);

Parameters: We can use the following parameters for the special formats parsing:

  • String: It is the DateTime that has to be parsed.
  • CUSTOM_FORMAT: A custom format can be specified here. It can also be specified using the HTML5_FMT when dates have to be directly parsed from the browser input elements.

HTML5_FMT property has the following available constants:

Constant Format Input Type
MONTH YYYY-MM <input type=”month” />
DATE YYYY-MM-DD <input type=”date” />
TIME HH: mm <input type=”time” />
WEEK GGGG-[W]WW <input type=”week” />
TIME_SECONDS HH:mm:ss <input type=”time” step=”1″ />

Return Value: This function returns the standard time and duration display.

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

The following examples will help to understand the Special Format parsing.

Example 1: 

Javascript




const moment = require("moment");
  
let special_formats1 =
    moment("2021-05-07T02:30:45", moment.ISO_8601);
console.log(special_formats1);
  
let special_formats2 =
    moment("2022-09-21", ["YYYY-MM", moment.ISO_8601]);
console.log(special_formats2);


Output:

Moment<2021-05-07T02:30:45+05:30>
Moment<2022-09-21T00:00:00+05:30>

Example 2: 

Javascript




const moment = require("moment");
  
let date1 = moment("2022-06-15T15:00:00",
            moment.HTML5_FMT.DATETIME_LOCAL_SECONDS);
let date2 = moment("2022-W50", moment.HTML5_FMT.WEEK);
let date3 = moment("2022-05", moment.HTML5_FMT.MONTH);
  
console.log("Date 1:", date1);
console.log("Date 2:", date2);
console.log("Date 3:", date3);


Output:

Date 1: Moment<2022-06-15T15:00:00+05:30>
Date 2: Moment<2022-12-12T00:00:00+05:30>
Date 3: Moment<2022-05-01T00:00:00+05:30>

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads