Categories
JavaScript JavaScript Basics

Formatting Dates with Moment Date Format

Spread the love

With moment.js, we can format dates easily with moment.js.

The list of formatting code that we can use with moment.js are below:

Year, Month, and Day Tokens

  • YYYY – 4 or 2 digit year
  • YY – 2 digit year
  • Y – year with any number of digits and sign
  • Q – quarter of year from 1 to 4
  • M MM – month number
  • MMM MMMM – month name according to the locale
  • D DD – day of the month
  • Do – day of the year
  • X – UNIX timestamp
  • x – UNIX mx timestamp

Week Year, Week, and Weekday Tokens

  • gggg – locale 4 digit week year
  • gg – locale 2 digit week year
  • w ww – locale week of year
  • e – locale day of week
  • ddd dddd – day name
  • GGGG – ISO 4 digit week year
  • GG – ISO 2 digit week year
  • W WW – ISO week of year
  • E – ISO day of week

Locale Aware Formats

  • L – date (in locale format)
  • LL – month name, day of month, year
  • LLL – month name, day of month, year, time
  • LLLL – day of week, month name, day of month, year, time
  • LT – time without seconds
  • LTS – time with seconds

Hour, Minute, Second, Millisecond, and Offset Tokens

  • H HH – hours in 24-hour format from 0 to 23
  • h hh – hours in 12 hours format
  • k kk – hours in 24 hour time from 1 to 24
  • a A – am or pm
  • m mm – minutes
  • s ss – seconds
  • S SS SSS – fractional seconds
  • Z ZZ – offset from UTC

For instance, we can call the format method as follows:

import moment from "moment";
const formattedTime = moment("2010-10-20 4:30").format("YYYY-MM-DD HH:mm");
console.log(formattedTime);

In the code above, we created a moment object with the moment factory function, and then call the format with the format string.

The formatting string is the combination of the parts that are listed above.

It’s very powerful and we can use it to format dates however we like.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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