date format moment js code example

Example 1: moment format

moment().format('MMMM Do YYYY, h:mm:ss a'); // September 30th 2020, 2:48:17 pm
moment().format('dddd');                    // Wednesday
moment().format("MMM Do YY");               // Sep 30th 20
moment().format('YYYY [escaped] YYYY');     // 2020 escaped 2020
moment().format();                          // 2020-09-30T14:48:17+02:00

Example 2: moment format date

moment.locale();         // en
moment().format('LT');   // 12:25 PM
moment().format('LTS');  // 12:25:27 PM
moment().format('L');    // 03/26/2021
moment().format('l');    // 3/26/2021
moment().format('LL');   // March 26, 2021
moment().format('ll');   // Mar 26, 2021
moment().format('LLL');  // March 26, 2021 12:25 PM
moment().format('lll');  // Mar 26, 2021 12:25 PM
moment().format('LLLL'); // Friday, March 26, 2021 12:25 PM
moment().format('llll'); // Fri, Mar 26, 2021 12:25 PM

Example 3: format a date moment

moment(testDate).format('MM/DD/YYYY');

Example 4: moment.js format

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

Example 5: moment.set

moment().set('year', 2013);
moment().set('month', 3);  // April
moment().set('date', 1);
moment().set('hour', 13);
moment().set('minute', 20);
moment().set('second', 30);
moment().set('millisecond', 123);

moment().set({'year': 2013, 'month': 3});

Example 6: moment format date

moment().subtract(10, 'days').calendar(); // 03/16/2021
moment().subtract(6, 'days').calendar();  // Last Saturday at 12:25 PM
moment().subtract(3, 'days').calendar();  // Last Tuesday at 12:25 PM
moment().subtract(1, 'days').calendar();  // Yesterday at 12:25 PM
moment().calendar();                      // Today at 12:25 PM
moment().add(1, 'days').calendar();       // Tomorrow at 12:25 PM
moment().add(3, 'days').calendar();       // Monday at 12:25 PM
moment().add(10, 'days').calendar();      // 04/05/2021

Tags: