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 yearYY
– 2 digit yearY
– year with any number of digits and signQ
– quarter of year from 1 to 4M MM
– month numberMMM MMMM
– month name according to the localeD DD
– day of the monthDo
– day of the yearX
– UNIX timestampx
– UNIX mx timestamp
Week Year, Week, and Weekday Tokens
gggg
– locale 4 digit week yeargg
– locale 2 digit week yearw ww
– locale week of yeare
– locale day of weekddd dddd
– day nameGGGG
– ISO 4 digit week yearGG
– ISO 2 digit week yearW WW
– ISO week of yearE
– ISO day of week
Locale Aware Formats
L
– date (in locale format)LL
– month name, day of month, yearLLL
– month name, day of month, year, timeLLLL
– day of week, month name, day of month, year, timeLT
– time without secondsLTS
– time with seconds
Hour, Minute, Second, Millisecond, and Offset Tokens
H HH
– hours in 24-hour format from 0 to 23h hh
– hours in 12 hours formatk kk
– hours in 24 hour time from 1 to 24a A
– am or pmm mm
– minutess ss
– secondsS SS SSS
– fractional secondsZ 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.