MomentJS - Format



This method will display the date/time details. It displays output based on the input. For example, moment().format("MMMMD") will display April for MMMM, that is the current month and current date for D. So the output is April16. With format, it tries to convert the units given to the corresponding display of date/time.

Syntax

moment().format();
moment().format(String);

Observe the following examples to gain a better understanding on displaying date using the format method.

Example

var changeddate = moment().format();

Output

Format

Note that when you use only the format method, it displays current Date and Time as shown above.

The following table shows a list of tokens to be taken as input string for format method −

Unit Token Output
Month M 1-12
Mo 1-12
MM 01-12
MMM Jan-Dec
MMMM January-December
Quarter Q 1-4
Qo 1st-4th
Day of Month D 1-31
Do 1st-31st
DD 01-31
Day of Year DDD 1-365
DDDo 1st-365th
DDDD 001-365
Day of Week d 0-6
do 0th-6th
dd Su,Mo,Tu,We,Th,Fr,Sa
ddd Sun-Sat
dddd Sunday-Saturday
Day of Week (locale) e 0-6
Day of Week(ISO) E 1-7
Week of Year w 1-53
wo 1st-53rd
ww 01-53
Week of Year(ISO) W 1-53
Wo 1st-53rd
WW 01-53
Year YY 70,71---29,30
YYYY 1970-2030
Y 1970-9999
Week Year gg 70,71 - 29,30
gggg 1970,1971-2030
Week Year (ISO) GG 70,71 - 29,30
GGGG 1970,1971-2030
AM/PM A AM, PM
a am,pm
Hour H 0-23
HH 00-23
h 1-12
hh 01-12
k 1-24
kk 01-24
Minute m 0-59
mm 00-59
Second s 0-59
ss 00-59
Fractional Second S 0-9
SS 00-99
SSS 000-999
SSSS…. 0000..-9999...
Time Zone Z -07:00 -06:00 ... +06:00 +07:00
ZZ -0700 -0600 ... +0600 +0700
Unix Timestamp X 1360013296
Unix Millisecond Timestamp x 1360013296123

The following table shows a list of tokens to be used on moment based on locale −

Unit Token Output
Time LT 2:58 PM
Time with seconds LTS 2:58:25 PM
Month numeral, day of month, year L 16/04/2018
I 16/4/2018
Month name, day of month, year LL April 16, 2018
II Apr 16, 2018
Month name, day of month, year, time LLL April 16, 2018 2:58 PM
III Apr 16, 2018 2:58 PM
Month name, day of month, day of week, year, time LLLL Monday, April 16, 2018,2:58 PM
IIII Mon, Apr 16, 2018, 2:58 PM

Observe the following examples to gain better understanding on token passed to format −

Example 1

var changeddate = moment().format("Do dddd MMMM gggg");

Output

Date Format

Example 2

var changeddate = moment().format("MMMM Qo DD YYYY");

Output

Date Moment

Example 3

You can also add characters to the format method. For this purpose, put them in square brackets as shown below −

var changeddate = moment().format("[Today's Date is ] D MMM YYYY");

Output

Date Characters

Example 4

var changeddate = moment().format("[Current Time is ] LTS");

Output

Date Current Time

Example 5

var changeddate = moment().format("[As per locale the date is ] LLLL");

Output

Date Changedate
momentjs_formatting_date_and_time.htm
Advertisements