Essential Moment.js Methods: A Complete Guide

This article provides a comprehensive reference for Moment.js, covering how to add or subtract time, set moments to the start or end of units, format dates with tokens, handle localization, compute relative times, and convert moments to native values, all illustrated with concrete code examples.

Full-Stack Trendsetter
Full-Stack Trendsetter
Full-Stack Trendsetter
Essential Moment.js Methods: A Complete Guide

add()

Changes the original moment by adding time. It is a robust feature that accepts a key and a quantity, a duration, or an object literal.

moment().add(Number, String);
moment().add(Duration);
moment().add(Object);

Example adding 7 days: moment().add(7, 'days'); Short keys can be used for brevity: moment().add(7, 'd'); years – y

quarters – Q

months – M

weeks – w

days – d

hours – h

minutes – m

seconds – s

milliseconds – ms

Multiple keys can be added either by chaining or by passing an object literal:

moment().add(7, 'days').add(1, 'months'); // chain
moment().add({days:7,months:1}); // object literal

subtract()

Changes the original moment by subtracting time, mirroring moment#add but with subtraction.

moment().subtract(Number, String);
moment().subtract(Duration);
moment().subtract(Object);

Example:

moment().subtract(7, 'days');

startOf()

Sets the moment to the beginning of a specified unit. moment().startOf(String); Examples:

moment().startOf('year');    // Jan 1 00:00 of current year
moment().startOf('month');   // 1st day 00:00 of current month
moment().startOf('quarter'); // start of current quarter
moment().startOf('week');    // start of ISO week
moment().startOf('day');     // today 00:00
moment().startOf('hour');    // current hour, minutes/seconds/ms set to 0
moment().startOf('minute');  // current minute, seconds/ms set to 0
moment().startOf('second');  // equivalent to moment().milliseconds(0)

These shortcuts are equivalent to setting each component manually:

moment().startOf('year');
moment().month(0).date(1).hours(0).minutes(0).seconds(0).milliseconds(0);
moment().startOf('hour');
moment().minutes(0).seconds(0).milliseconds(0);

endOf()

Sets the moment to the end of a specified unit, the counterpart of startOf. moment().endOf(String); Example:

moment().endOf('year'); // Dec 31 23:59:59.999 of current year

format()

Formats a moment into a string using token strings.

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

Examples:

moment().format(); // "2014-09-08T08:02:17-05:00"
moment().format('dddd, MMMM Do YYYY, h:mm:ss a'); // "Sunday, February 14th 2010, 3:25:50 pm"
moment().format('ddd, hA'); // "Sun, 3PM"
moment('gibberish').format('YYYY MM DD'); // "Invalid date"

Month – M – 1 2 … 12

Mo – 1st 2nd … 12th

MM – 01 02 … 12

MMM – Jan Feb … Dec

MMMM – January February … December

Quarter – Q – 1 2 3 4

Qo – 1st 2nd 3rd 4th

Day of month – D – 1 2 … 31

Do – 1st 2nd … 31st

DD – 01 02 … 31

Day of year – DDD – 1 2 … 365

DDDo – 1st 2nd … 365th

DDDD – 001 002 … 365

Weekday – d – 0 1 … 6

do – 0th 1st … 6th

dd – Su Mo … Sa

ddd – Sun Mon … Sat

dddd – Sunday Monday … Saturday

Locale weekday – e – 0 1 … 6

ISO weekday – E – 1 2 … 7

Week of year – w – 1 2 … 53

wo – 1st 2nd … 53rd

ww – 01 02 … 53

ISO week of year – W – 1 2 … 53

Wo – 1st 2nd … 53rd

WW – 01 02 … 53

Year – YY – 70 71 … 30

YYYY – 1970 1971 … 2030

Y – 1970 1971 … 9999 (+10000 …)

Era – gg – 70 71 … 30

gggg – 1970 1971 … 2030

GG – 70 71 … 30

GGGG – 1970 1971 … 2030

Meridiem – A – AM PM

a – am pm

Hour (24‑hour) – H – 0 1 … 23

HH – 00 01 … 23

Hour (12‑hour) – h – 1 2 … 12

hh – 01 02 … 12

Minute – m – 0 1 … 59

mm – 00 01 … 59

Second – s – 0 1 … 59

ss – 00 01 … 59

Fractional second – S – 0 1 … 9

SS – 00 01 … 99

SSS – 000 001 … 999

SSSS… – 000[0..] …

Timezone – z / zz – EST CST … (deprecated from 1.6.0)

Z – -07:00 … +07:00

ZZ – -0700 … +0700

Unix timestamp – X – 1360013296

Unix millisecond timestamp – x – 1360013296123

Localized format tokens are available from version 2.0.0; LTS was added in 2.8.4.

Escaping characters

Wrap characters in square brackets to escape them in format strings.

moment().format('[今天] dddd'); // "今天 Sunday"

fromNow()

moment().fromNow();
moment().fromNow(Boolean);

Displays relative time from now. Passing true returns the value without the suffix.

moment([2007, 0, 29]).fromNow(); // "4 years ago"
moment([2007, 0, 29]).fromNow(true); // "4 years"

from()

moment().from(Moment|String|Number|Date|Array);
moment().from(Moment|String|Number|Date|Array, Boolean);

Shows relative time from a given moment to another. The first argument can be any value accepted by moment() or an actual Moment instance.

var a = moment([2007, 0, 28]);
var b = moment([2007, 0, 29]);
a.from(b); // "1 day ago"

Passing true as the second argument returns the value without the suffix.

var start = moment([2007, 0, 5]);
var end   = moment([2007, 0, 10]);
end.from(start, true); // "5 days"

toNow()

moment().toNow();
moment().toNow(Boolean);

Similar to fromNow but returns the opposite interval ( a.fromNow() = - a.toNow()).

moment([2007, 0, 29]).toNow(); // "in 4 years"
moment([2007, 0, 29]).toNow(true); // "4 years"

to()

moment().to(Moment|String|Number|Date|Array);
moment().to(Moment|String|Number|Date|Array, Boolean);

Shows relative time from the current moment to another moment.

var a = moment([2007, 0, 28]);
var b = moment([2007, 0, 29]);
a.to(b); // "in 1 day"

Passing true as the second argument returns the value without the suffix.

var start = moment([2007, 0, 5]);
var end   = moment([2007, 0, 10]);
end.to(start, true); // "5 days"

From version 2.10.3, an invalid endpoint yields a localized "Invalid date" string.

valueOf()

moment().valueOf();
+moment();

Outputs the milliseconds since the Unix epoch, similar to Date#valueOf.

moment(1318874398806).valueOf(); // 1318874398806
+moment(1318874398806); // 1318874398806

Use moment#unix to get the Unix timestamp in seconds.

unix()

moment().unix();

Returns the Unix timestamp (seconds since epoch). The value is rounded down to the nearest second.

moment(1318874398806).unix(); // 1318874398

daysInMonth()

moment().daysInMonth();

Returns the number of days in the current month.

moment('2012-02', 'YYYY-MM').daysInMonth(); // 29
moment('2012-01', 'YYYY-MM').daysInMonth(); // 31

toDate()

moment().toDate();

Returns a copy of the native Date object encapsulated by the moment. Modifying the returned Date does not affect the original moment; to manipulate the moment itself, use moment#manipulate or moment#set.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptformattingmoment.jstime zonesdate manipulationrelative time
Full-Stack Trendsetter
Written by

Full-Stack Trendsetter

Latest articles, video tutorials, and open-source projects on React, Vue, Angular, Ionic, React Native, Node.js, Mini Programs, and other cutting-edge technologies. A community for sharing and discussing full-stack development trends.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.