How to Format Date and Time with Moment.js

Today we will learn irritating work in web development which is date and time formatting , So we will learn how to manage it with easy to use library which is moment.js

npm install moment --save   # npm
OR 
yarn add moment
  • Format Dates

 

moment().format('MMMM Do YYYY, h:mm:ss a') // January 22th 2023, 11:07:47 am
moment().format('dddd');                   // Thursday
moment().format("MMM Do YY");              // Jan 22th 23
moment().format('YYYY [escaped] YYYY');    // 2023 escaped 2023
moment().format();                         // 2023-01-22T11:07:47+05:30
  • Relative Time

moment("20111031", "YYYYMMDD").fromNow(); // 11 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 11 years ago
moment().startOf('day').fromNow();        // 11 hours ago
moment().endOf('day').fromNow();          // in 13 hours
moment().startOf('hour').fromNow();       // 11 minutes ago
  • Calendar Time

moment().subtract(10, 'days').calendar(); // 01/16/2023
moment().subtract(6, 'days').calendar();  // Last Friday at 11:13 AM
moment().subtract(3, 'days').calendar();  // Last Monday at 11:13 AM
moment().subtract(1, 'days').calendar();  // Yesterday at 11:13 AM
moment().calendar();                      // Today at 11:13 AM
moment().add(1, 'days').calendar();       // Tomorrow at 11:13 AM
moment().add(3, 'days').calendar();       // Sunday at 11:13 AM
moment().add(10, 'days').calendar();      // 02/05/2023
  • Multiple Locale Support

moment.locale();         // en
moment().format('LT');   // 11:13 AM
moment().format('LTS');  // 11:13:45 AM
moment().format('L');    // 01/22/2023
moment().format('l');    // 1/22/2023
moment().format('LL');   // January 22, 2023
moment().format('ll');   // Jan 22, 2023
moment().format('LLL');  // January 22, 2023 11:13 AM
moment().format('lll');  // Jan 22, 2023 11:13 AM
moment().format('LLLL'); // Thursday, January 22, 2023 11:13 AM
moment().format('llll'); // Thu, Jan 22, 2023 11:14 AM

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories