Moment.js is a JavaScript library that works with dates and times for parsing, manipulating, and formatting dates.
Whether you’re building a web application, mobile app, or other projects that involve working with dates and times, Moment.js can help you easily achieve your goals.
Install Moment.js Package:
npm install moment
Parse a date string in ISO format:
const moment = require("moment"); let dateStr = '2022-02-26T10:20:30Z'; let date = moment(dateStr);
Format Displaying Syntax:
Month:
M = 1 2 … 11 12
MM = 01 02 … 11 12
MMM = Jan Feb … Nov Dec
MMMM = January February … November December
Day of Month:
D = 1 2 … 30 31
DD = 01 02 … 30 31
Year:
YY = 70 71 … 29 30
YYYY = 1970 1971 … 2029 2030
Format Dates
let date_Str = '2022-02-26T10:20:30Z'; let date = moment(date_Str); console.log(date.format('MMMM Do YYYY, h:mm:ss a')); console.log(date.format('dddd')); console.log(date.format("MMM Do YY")); console.log(date.format('YYYY [escaped] YYYY')); console.log(date.format());
Manipulating Dates :
In addition to parsing and displaying dates, Moment.js also provides a wide range of functions for manipulating dates. Whether you need to add or subtract days, weeks, months, or years, Moment.js has you covered.
let date_Str = '2022-02-26T10:20:30Z'; let date = moment(date_Str); console.log(date.add(2, 'day').format("MMM Do YYYY")); console.log(date.add(4, 'months').format("MMM Do YYYY")); console.log(date.add(2, 'years').format("MMM Do YYYY")); console.log(date.subtract(1, 'years').format("MMM Do YYYY"));
for more ref link.