Moment.js Documentation

Get the current version 1.6.2

npm install moment

Production (4.3k min & gzip)

Development (full 31.2k source)

Where to use it

Moment was designed to work in both the browser and in NodeJS. All code will work in both environments. All unit tests are run in both environments.

In NodeJS

 
var moment = require('moment');

moment().add('hours', 1).fromNow(); // "1 hour ago"

In the Browser

 
<script src="moment.min.js"></script>

moment().add('hours', 1).fromNow(); // "1 hour ago"

Parse

Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object.

Note: The Moment.js prototype is exposed through moment.fn. If you want to add your own functions, that is where you would put them.

To get this wrapper object, simply call moment() with one of the supported input types.

Javascript Date Object

moment(Date);
Available in version 1.0.0
 

You can create a moment with a pre-existing native Javascript Date object.

var day = new Date(2011, 9, 16);

var dayWrapper = moment(day); 
var otherDay = moment(new Date(2020, 3, 7));

This is the fastest way to get a Moment.js wrapper.

Milliseconds since the Unix Epoch

moment(Number);
Available in version 1.0.0
 

Similar to new Date(Number), you can create a moment by passing an integer value representing the number of milliseconds since the Unix Epoch (1 January 1970 00:00:00 UTC).

var day = moment(1318781876406);

Note: To create a moment()from a Unix timetamp (the number of seconds since the Epoch), use moment.unix(Number).

Unix Timestamp

moment.unix(Number)
Available in version ???
 

You can create a moment from a Unix timestamp (seconds since the Unix Epoch) using moment.unix(Number).

var day = moment(1318781876);

Note: This functions is implemented with (approximately)return moment(timestamp * 1000), so milliseconds in the input timestamp will be included in the moment.

String

moment(String);
Available in version 1.0.0
 

You can create a moment from a string that can be parsed by Date.parse.

var day = moment("Dec 25, 1995");

Browser support for this is somewhat inconsistent. If you are not getting consistent results, you can try using String + Format.

If you are trying to parse an ISO-8601 string, the following formats are supported across all browsers.

"YYYY-MM-DD"
"YYYY-MM-DDTHH"
"YYYY-MM-DDTHH:mm"
"YYYY-MM-DDTHH:mm:ss"
"YYYY-MM-DDTHH:mm:ss z"

Note: Automatic cross browser ISO-8601 support was added in version 1.5.0

String + Format

moment(String, String);
Available in version 1.0.0
 

If you know the format of an input string, you can use that to parse a moment.

var day = moment("12-25-1995", "MM-DD-YYYY");

The format parsing tokens are similar to the tokens for moment.fn.format.

The parser ignores non-alphanumeric characters, so both moment("12-25-1995", "MM-DD-YYYY")and moment("12\25\1995", "MM-DD-YYYY")will return the same thing.

InputOutput
M or MMMonth Number (1 - 12)
MMM or MMMMMonth Name (In currently language set by moment.lang())
D or DDDay of month
DDD or DDDDDay of year
d, dd, ddd, or ddddDay of week (NOTE: these tokens are not used to create the date, as there are 4-5 weeks in a month, and it would be impossible to get the date based off the day of the week)
YY2 digit year (if greater than 70, will return 1900's, else 2000's)
YYYY4 digit year
a or AAM/PM
H, HH24 hour time
h, or hh12 hour time (use in conjunction with a or A)
m or mmMinutes
s or ssSeconds
SDeciseconds (1/10th of a second)
SSCentiseconds (1/100th of a second)
SSSMilliseconds (1/1000th of a second)
Z or ZZTimezone offset as +0700 or +07:30

Available in version 1.2.0

Unless you specify a timezone offset, parsing a string will create a date in the current timezone.

A workaround to parse a string in UTC is to append "+0000" to the end of your input string, and add "ZZ" to the end of your format string.

Warning Parsing a string with a format is by far the slowest method of creating a date. If you have the ability to change the input, it is much faster (~15x) to use milliseconds since the Unix Epoch or Unix timestamps.

String + Formats

moment(String, String[]);
Available in version 1.0.0
 

If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.

This is the same as String + Format, only it will try to match the input to multiple formats.

var day = moment("12-25-1995", ["MM-DD-YYYY", "YYYY-MM-DD"]);

This approach is fundamentally problematic in cases like the following, where there is a difference in big, medium, or little endian date formats.

var day = moment("05-06-1995", ["MM-DD-YYYY", "DD-MM-YYYY"]); // June 5th or May 6th?

Warning THIS IS SLOW. This should only be used as a last line of defense.

Now

moment();
Available in version 1.0.0
 

To get the current date and time, just call moment()with no parameters.

var now = moment();

This is essentially the same as calling moment(new Date()).

Javascript Array

moment(Number[]);
Available in version 1.0.0
 

You can also create a moment by passing in an array of the parameters that mirror the parameters passed to new Date()

[year, month = 0, date = 1, hours = 0, minutes = 0, seconds = 0, milliseconds = 0] 

var day = moment([2010, 1, 14, 15, 25, 50, 125]); // February 14th, 3:25:50.125 PM

Any value past the year is optional, and will default to the lowest possible number.

var day = moment([2010]); // January 1st 

var day = moment([2010, 6]); // July 1st 
var day = moment([2010, 6, 10]); // July 10th

Construction with an array will create a date in the current timezone. To create a date from an array at UTC, you can use the following.

var array = [2010, 1, 14, 15, 25, 50, 125];

var day = moment(Date.UTC.apply({}, array));

Note: Because this mirrors the native Date parameters, the following parameters are all zero indexed: months, hours, minutes, seconds, and milliseconds. Years and days of the month are 1 indexed.

This is often the cause of frustration, especially with months, so take note!

ASP.NET json dates

moment(String);
Available in version 1.3.0
 

ASP.NET returns dates in json in the following formats: /Date(1198908717056)/ or /Date(1198908717056-0700)/

If a string that matches this format is passed in, it will be parsed correctly.

moment("/Date(1198908717056-0700)/").valueOf(); // 1198908717056

Cloning

moment(Moment);
Available in version 1.2.0
 

All moments are mutable. If you want a clone of a moment, you can do so explicitly or implicitly.

Calling moment() on a moment will clone it.

var a = moment([2012]);

var b = moment(a);
a.year(2000);
b.year(); // 2012

Additionally, you can call moment.fn.clone to clone a moment.

var a = moment([2012]);

var b = a.clone();
a.year(2000);
b.year(); // 2012

UTC

moment.utc();
moment.utc(Number);
moment.utc(Number[]);
moment.utc(String);
moment.utc(String, String);
Available in version 1.5.0
 

By default, moment parses in local time. If you want to parse a moment in UTC, you can use the following methods.

moment.utc() // current date/time in UTC mode
moment.utc(Number) // milliseconds since the Unix Epoch in UTC mode
moment.utc([Number, ...]) // parse an array of numbers matching Date.UTC() parameters
moment.utc(String) // parse string into UTC mode
moment.utc(String, String) // parse a string and format into UTC mode

This brings us to an interesting feature of moment.js, UTC mode.

While in UTC mode, all display methods will display in UTC time instead of local time.

Any moment created with moment() will not be in UTC mode, and any moments created with moment.utc() will be in UTC mode.

To switch from UTC to local time, you can usemoment.fn.utc ormoment.fn.local.

var a = moment.utc([2011, 0, 1, 8]);
a.hours(); // 8 UTC
a.local();
a.hours(); // 0 PST

Manipulate

Once you have a Moment.js wrapper object, you may want to manipulate it in some way. There are a number of moment.fn methods to help with this.

All manipulation methods are chainable, so you can do crazy things like this.

moment().add('days', 7).subtract('months', 1).year(2009).hours(0).minutes(0).seconds(0);

Note: It should be noted that moments are mutable. Calling any of the manipulation methods will change the original moment.

If you want to create a copy and manipulate it, you should use moment.fn.clone before manipulating the moment. More info on cloning.

Add

moment().add(String, Number);
moment().add(Object);
Available in version 1.0.0
 

This is a pretty robust function for adding time to an existing date. To add time, pass the key of what time you want to add, and the amount you want to add.

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

There are some shorthand keys as well if you're into that whole brevity thing.

moment().add('d', 7);
KeyShorthand
yearsy
monthsM
weeksw
daysd
hoursh
minutesm
secondss
millisecondsms

If you want to add multiple different keys at the same time, you can pass them in as an object literal.

moment().add('days', 7).add('months', 1); // with chaining 

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

There are no upper limits for the amounts, so you can overload any of the parameters.

moment().add('milliseconds', 1000000); // a million milliseconds 

moment().add('days', 360); // 360 days

Special considerations for months and years

If the day of the month on the original date is greater than the number of days in the final month, the day of the month will change to the last day in the final month.

Example:

moment([2010, 0, 31]);                  // January 31 

moment([2010, 0, 31]).add('months', 1); // February 28

There are also special considerations to keep in mind when adding time that crosses over Daylight Savings Time. If you are adding years, months, weeks, or days, the original hour will always match the added hour.

var m = moment(new Date(2011, 2, 12, 5, 0, 0)); // the day before DST in the US

m.hours(); // 5
m.add('days', 1).hours(); // 5

If you are adding hours, minutes, seconds, or milliseconds, the assumption is that you want precision to the hour, and will result in a different hour.

var m = moment(new Date(2011, 2, 12, 5, 0, 0)); // the day before DST in the US

m.hours(); // 5
m.add('hours', 24).hours(); // 6

Subtract

moment().subtract(String, Number);
moment().subtract(Object);
Available in version 1.0.0
 

This is exactly the same as moment.fn.add, only instead of adding time, it subtracts time.

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

Milliseconds

moment().milliseconds(Number);
Available in version 1.3.0
 

There are a number of shortcut getter and setter functions. Much like in jQuery, calling the function without paremeters causes it to function as a getter, and calling with a parameter causes it to function as a setter.

These map to the corresponding function on the native Dateobject.

 
moment().milliseconds(30) === new Date().setMilliseconds(30);
moment().milliseconds()   === new Date().getMilliseconds();

If you are in UTC mode, they will map to the UTC equivalent.

 
moment.utc().milliseconds(30) === new Date().setUTCMilliseconds(30);
moment.utc().milliseconds()   === new Date().getUTCMilliseconds();

Accepts numbers from 0 to 999

Seconds

moment().seconds(Number);
Available in version 1.0.0
 

Accepts numbers from 0 to 59

moment().seconds(30); // set the seconds to 30

Minutes

moment().minutes(Number);
Available in version 1.0.0
 

Accepts numbers from 0 to 59

moment().minutes(30); // set the minutes to 30

Hours

moment().hours(Number);
Available in version 1.0.0
 

Accepts numbers from 0 to 23

moment().hours(12); // set the hours to 12

Date of the Month

moment().date(Number);
Available in version 1.0.0
 

Accepts numbers from 1 to 31

moment().date(5); // set the date to 5

NOTE: moment.fn.date is used to set the date of the month, and moment.fn.day is used to set the day of the week.

Day of the Week

moment().day(Number);
Available in version 1.3.0
 
moment().day(5); // set the day of the week to Friday

This method can be used to set the day of the week, Sunday being 0 and Saturday being 6.

moment.fn.day can also be overloaded to set to a weekday of the previous week, next week, or a week any distance from the moment.

moment().day(-7); // set to last Sunday (0 - 7) 

moment().day(7); // set to next Sunday (0 + 7)
moment().day(10); // set to next Wednesday (3 + 7)
moment().day(24); // set to 3 Wednesdays from now (3 + 7 + 7 + 7)

Month

moment().month(Number);
Available in version 1.0.0
 

Accepts numbers from 0 to 11

moment().month(5); // set the month to June

Year

moment().year(Number);
Available in version 1.0.0
 
moment().year(1984); // set the year to 1984

Start of Day

moment().sod();
Available in version 1.4.0
 

Set the time to the start of the day.

moment().sod(); // set the time to last midnight

This is essentially the same as the following.

moment().hours(0).minutes(0).seconds(0).milliseconds(0);

End of Day

moment().eod();
Available in version 1.4.0
 

Set the time to the end of the day.

moment().eod(); // set the time to 11:59:59.999 pm tonight

This is essentially the same as the following.

moment().hours(23).minutes(59).seconds(59).milliseconds(999);

Local

moment().local();
Available in version 1.5.0
 

This method switches to local mode.

var a = moment.utc([2011, 0, 1, 8]);
a.hours(); // 8 UTC
a.local();
a.hours(); // 0 PST

UTC

moment().utc();
Available in version 1.5.0
 

This method switches to UTC mode.

var a = moment([2011, 0, 1, 8]);
a.hours(); // 8 PST
a.utc();
a.hours(); // 16 UTC

Display

Once parsing and manipulation are done, you need some way to display the moment. Moment.js offers many ways of doing that.

Format

moment().format();
moment().format(String);
Available in version 1.0.0
 

The most robust display option is moment.fn.format. It takes a string of tokens and replaces them with their corresponding values from the Date object.

var a = moment([2010, 1, 14, 15, 25, 50, 125]);

a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
a.format("ddd, hA");                       // "Sun, 3PM"
TokenOutput
Month
M1 2 ... 11 12
Mo1st 2nd ... 11th 12th
MM01 02 ... 11 12
MMMJan Feb ... Nov Dec
MMMMJanuary February ... November December
Day of Month
D1 2 ... 30 30
Do1st 2nd ... 30th 31st
DD01 02 ... 30 31
Day of Year
DDD1 2 ... 364 365
DDDo1st 2nd ... 364th 365th
DDDD001 002 ... 364 365
Day of Week
d0 1 ... 5 6
do0th 1st ... 5th 6th
dddSun Mon ... Fri Sat
ddddSunday Monday ... Friday Saturday
Week of Year
w1 2 ... 52 53
wo1st 2nd ... 52nd 53rd
ww01 02 ... 52 53
Year
YY70 71 ... 29 30
YYYY1970 1971 ... 2029 2030
AM/PM
AAM PM
aam pm
Hour
H0 1 ... 22 23
HH00 01 ... 22 23
h1 2 ... 11 12
hh01 02 ... 11 12
Minute
m0 1 ... 58 59
mm00 01 ... 58 59
Second
s0 1 ... 58 59
ss00 01 ... 58 59
Timezone
z or zzEST CST ... MST PST

Note: as of 1.6.0, the z/zz format tokens have been deprecated. Read more about it here.
Z-07:00 -06:00 ... +06:00 +07:00
ZZ-0700 -0600 ... +0600 +0700

Z and ZZ are available in version 1.2.0
Localized date format
LT8:30 PM

LT is available in version 1.3.0
L07/10/1986
LLJuly 10 1986
LLLJuly 10 1986 8:30 PM
LLLLSaturday, July 10 1986 8:30 PM

L, LL, LLL, LLLL are available in version 1.3.0

To escape characters in format strings, you can use a backslash before any character. NOTE: if you are using a string literal, you will need to escape the backslash, hence the double backslash below.

moment().format('\\L'); // outputs 'L'

To escape multiple characters, you can wrap the characters in square brackets.

moment().format('[today] DDDD'); // 'today Sunday'

Note: While these date formats are very similar to LDML date formats, there are a few minor differences regarding day of month, day of year, and day of week.

For a breakdown of a few different date formatting tokens, see this chart of date formatting tokens.

To compare moment.js date formatting speeds against other libraries, check out http://jsperf.com/date-formatting .

Baron Schwartz wrote a pretty cool date formatter that caches formatting functions to avoid expensive regex or string splitting. It's so much faster than any of the other libraries, that it's best to compare it on its own, rather than pollute the "best of the uncompiled" formatting libs.

Here's the moment.js vs xaprb performance tests, and here is thearticle describing his methods.

If you are more comfortable working with strftime instead of LDML-like parsing tokens, you can use Ben Oakes' plugin moment-strftime .

It is available on npm.

npm install moment-strftime

The repository is located at benjaminoakes/moment-strftime

Note: As of version1.5.0, calling this function without any parameters will output ISO-8601.

It will use moment.defaultFormat to format the moment, which by default is YYYY-MM-DDTHH:mm:ssZ.

Humanize time from another moment

moment().from(Moment);
moment().from(Moment, Boolean);
Available in version 1.0.0
 

Another common way of displaying time, sometimes called timeago, is handled by moment.fn.from.

var a = moment([2007, 0, 29]);

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

The first parameter is anything you can pass to moment()or a Moment.js object.

var a = moment([2007, 0, 29]);

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

NOTE: Because it only accepts one parameter to pass in the date info, if you need to use String + Format or String + Formats, you should create a Moment.js object first and then call moment.fn.from

var a = moment();

var b = moment("10-10-1900", "MM-DD-YYYY");
a.from(b);

If you pass trueas the second parameter, you can get the value without the suffix. This is useful wherever you need to have a human readable length of time.

var start = moment([2007, 0, 5]);

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

The base strings are customized by moment.langor by modifying the values directly using moment.relativeTime.

The breakdown of which string is displayed when is outlined in the table below.

RangeKeySample Output
0 to 45 secondssseconds ago
45 to 90 secondsma minute ago
90 seconds to 45 minutesmm2 minutes ago ... 45 minutes ago
45 to 90 minuteshan hour ago
90 minutes to 22 hours hh2 hours ago ... 22 hours ago
22 to 36 hoursda day ago
36 hours to 25 daysdd2 days ago ... 25 days ago
25 to 45 daysMa month ago
45 to 345 daysMM2 months ago ... 11 months ago
345 to 547 days (1.5 years)ya year ago
548 days+yy2 years ago ... 20 years ago

Humanize time from now

moment().fromNow();
moment().fromNow(Boolean);
Available in version 1.0.0
 

This is just a map to moment.fn.from(new Date())

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

Like moment.fn.from, if you pass trueas the second parameter, you can get the value without the suffix.

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

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

Humanize duration

moment.humanizeDuration(Number);
moment.humanizeDuration(Number, String);
moment.humanizeDuration(Number, String, Boolean);
Available in version 1.5.0
 

Note:moment.humanizeDuration() has been deprecated in favor of moment.duration().humanize().

It will be removed shortly in the future. More documentation on moment.duration().humanize() here.

Sometimes, you want all the goodness of moment.fn.from but you don't want to have to create two moments, you just want to display a length of time.

Enter moment.humanizeDuration. With only a number passed in, it will return the humanized duration of the number as milliseconds.

moment.humanizeDuration(1000 * 60); // a minute

To use a different time difference, pass it in as a string.

moment.humanizeDuration(1, "seconds"); // a few seconds
moment.humanizeDuration(1, "minutes"); // a minute
moment.humanizeDuration(1, "hours");   // an hour
moment.humanizeDuration(1, "days");    // a day
moment.humanizeDuration(1, "weeks");   // 7 days
moment.humanizeDuration(1, "months");  // a month
moment.humanizeDuration(1, "years");   // a year

By default, the return string is suffixless. If you want a suffix, pass in true as seen below.

moment.humanizeDuration(60000, true);        // in a minute
moment.humanizeDuration(1, "minutes", true); // in a minute

For suffixes before now, pass in a negative number.

moment.humanizeDuration(-60000, true);        // a minute ago
moment.humanizeDuration(-1, "minutes", true); // a minute ago

Calendar Time

moment().calendar();
Available in version 1.3.0
 

Calendar time is displays time relative to now, but slightly differently than moment.fn.from.

moment.fn.calendar will format a date with different strings depending on how close to today the date is.

Last weekLast Monday 2:30 AM
The day beforeYesterday 2:30 AM
The same dayToday 2:30 AM
The next dayTomorrow 2:30 AM
The next weekSunday 2:30 AM
Everything else7/10/2011

These strings are localized, and can be customized with moment.calendar or moment.lang.

Difference

moment().diff(Moment);
moment().diff(Moment, String);
moment().diff(Moment, String, Boolean);
Available in version 1.0.0
 

To get the difference in milliseconds, use moment.fn.diff like you would use moment.fn.from.

var a = moment([2007, 0, 29]);

var b = moment([2007, 0, 28]);
a.diff(b) // 86400000

To get the difference in another unit of measurement, pass that measurement as the second argument.

var a = moment([2007, 0, 29]);

var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

The supported measurements are "years", "months", "weeks", "days", "hours", "minutes", and "seconds"

By default, moment.fn.diffwill return a rounded number. If you want the floating point number, pass true as the third argument.

var a = moment([2007, 0]);

var b = moment([2008, 5]);
a.diff(b, 'years')       // 1
a.diff(b, 'years', true) // 1.5

Units of measurement other than milliseconds are available in version 1.1.1

If the moment is later than the moment you are passing to moment.fn.diff, the return value will be negative.

var a = moment();
var b = moment().add('seconds', 1);
a.diff(b) // -1000
b.diff(a) // 1000

A easy way to think of this is by replacing .diff( with a minus operator.

          // a < b
a.diff(b) // a - b < 0
b.diff(a) // b - a > 0

Native Javascript Date

moment().toDate();
Available in version 1.0.0
 

To get the native Date object that Moment.js wraps, use moment.fn.toDate.

moment([2007, 0, 29]).toDate(); // returns native Date object

Note: moment.fn.native has been replaced by moment.fn.toDate and has been deprecated as of1.6.0.

Milliseconds since the Unix Epoch

moment().valueOf();
Available in version 1.0.0
 

moment.fn.valueOf simply outputs the number of milliseconds since the Unix Epoch, just like JavaScript's native Date.valueOf().

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

Note: To get a Unix timestamp (the number of seconds since the Epoch) from a moment(), use moment.fn.unix().

Unix Timestamp

moment().unix();
Available in version 1.6.0
 

moment.fn.unixsimply outputs a Unix timestamp (the of seconds since the Unix Epoch).

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

Note: This value is rounded to the nearest second, and does not include a milliseconds component.

Milliseconds

moment().milliseconds();
Available in version 1.3.0
 

Get the milliseconds (0 - 999).

Seconds

moment().seconds();
Available in version 1.0.0
 

Get the seconds (0 - 59).

Minutes

moment().minutes();
Available in version 1.0.0
 

Get the minutes (0 - 59).

Hours

moment().hours();
Available in version 1.0.0
 

Get the hours (0 - 23).

Date of the Month

moment().date();
Available in version 1.0.0
 

Get the date of the month (1 - 31).

Day of the Week

moment().day();
Available in version 1.0.0
 

Get the day of the week (0 - 6).

Month

moment().month();
Available in version 1.0.0
 

Get the month (0 - 11).

Year

moment().year();
Available in version 1.0.0
 

Get the four digit year.

Leap Year

moment().isLeapYear();
Available in version 1.0.0
 

moment.fn.isLeapYear returns true if that year is a leap year, and false if it is not.

moment([2000]).isLeapYear() // true

moment([2001]).isLeapYear() // false
moment([2100]).isLeapYear() // false

Timezone Offset

moment().zone();
Available in version 1.2.0
 

Get the timezone offset in minutes.

moment().zone(); // (60, 120, 240, etc.)

Days in Month

moment().daysInMonth();
Available in version 1.5.0
 

Get the number of days in the current month.

moment("2012-2", "YYYY-MM").daysInMonth() // 29

moment("2012-1", "YYYY-MM").daysInMonth() // 31

Daylight Saving Time

moment().isDST();
Available in version 1.2.0
 

moment.fn.isDST checks if the current moment is in daylight savings time or not.

moment([2011, 2, 12]).isDST(); // false, March 12 2011 is not DST

moment([2011, 2, 14]).isDST(); // true, March 14 2011 is DST

isMoment

moment.isMoment(obj);
Available in version 1.5.0
 

If you want to check if a variable is a moment object, you can use moment.isMoment().

moment.isMoment() // false
moment.isMoment(new Date()) // false
moment.isMoment(moment()) // true

i18n

Moment.js has pretty robust support for internationalization. You can load multiple languages onto the same instance and easily switch between them.

Changing languages

moment.lang(String);
moment.lang(String, Object);
Available in version 1.0.0
 

By default, Moment.js comes with English language strings. If you need other languages, you can load them into Moment.js for later use.

To load a language, pass the key and the string values to moment.lang.

Note: More details on each of the parts of the language bundle can be found in the customization section.

moment.lang('fr', {

    months : "Janvier_Février_Mars_Avril_Mai_Juin_Juillet_Aout_Septembre_Octobre_Novembre_Décembre".split("_"),
    monthsShort : "Jan_Fev_Mar_Avr_Mai_Juin_Juil_Aou_Sep_Oct_Nov_Dec".split("_"),
    weekdays : "Dimanche_Lundi_Mardi_Mercredi_Jeudi_Vendredi_Samedi".split("_"),
    weekdaysShort : "Dim_Lun_Mar_Mer_Jeu_Ven_Sam".split("_"),
    longDateFormat : { 
        L : "DD/MM/YYYY",
        LL : "D MMMM YYYY",
        LLL : "D MMMM YYYY HH:mm",
        LLLL : "dddd, D MMMM YYYY HH:mm"
    },
    meridiem : {
        AM : 'AM',
        am : 'am',
        PM : 'PM',
        pm : 'pm'
    },
    calendar : {
        sameDay: "[Ajourd'hui à] LT",
        nextDay: '[Demain à] LT',
        nextWeek: 'dddd [à] LT',
        lastDay: '[Hier à] LT',
        lastWeek: 'dddd [denier à] LT',
        sameElse: 'L'
    },
    relativeTime : {
        future : "in %s",
        past : "il y a %s",
        s : "secondes",
        m : "une minute",
        mm : "%d minutes",
        h : "une heure",
        hh : "%d heures",
        d : "un jour",
        dd : "%d jours",
        M : "un mois",
        MM : "%d mois",
        y : "une année",
        yy : "%d années"
    },
    ordinal : function (number) {
        return (~~ (number % 100 / 10) === 1) ? 'er' : 'ème';
    }
});

Once you load a language, it becomes the active language. To change active languages, simply call moment.lang with the key of a loaded language.

moment.lang('fr');

moment(1316116057189).fromNow() // il y a une heure
moment.lang('en');
moment(1316116057189).fromNow() // an hour ago 

Loading languages in NodeJS

moment.lang(String);
Available in version 1.0.0
 

Loading languages in NodeJS is super easy. If there is a language file in moment/lang/ named after that key, the first call to moment.lang will load it.

var moment = require('moment');

moment.lang('fr');
moment(1316116057189).fromNow(); // il y a une heure

If you want your language supported, create a pull request or send me an email with the required files.

Loading languages in the browser

moment.lang(String);
Available in version 1.0.0
 

Loading languages in the browser just requires you to include the language files.

<script src="moment.min.js"></script>

<script src="lang/fr.js"></script>
<script src="lang/pt.js"></script>

There are minified versions of each of these languages. There is also a minified version of all of the languages bundled together.

<script src="moment.min.js"></script>
<script src="lang/all.min.js"></script>

Ideally, you would bundle all the files you need into one file to minimize http requests.

<script src="moment-fr-it.min.js"></script>

Adding your language to Moment.js

 

To add your language to Moment.js, submit a pull request with both a language file and a test file. You can find examples in moment/lang/fr.js and moment/test/lang/fr.js.

To run the tests, do make test.

If all the tests pass, submit that pull request, and thank you for contributing!

Checking the current Moment.js language

moment.lang();
Available in version 1.6.0
 

If you are changing languages frequently, you may want to know what language is currently being used. This is as simple as calling moment.lang without any parameters.

moment.lang('en'); // set to english
moment.lang(); // returns 'en'
moment.lang('fr'); // set to french
moment.lang(); // returns 'fr'

Customize

If you don't need i18n support, you can manually override the customization values. However, any calls to moment.lang will override them. It is probably safer to create a language for your specific customizations than to override these values manually.

Month Names

moment.months = String[];
Available in version 1.0.0
 

moment.months should be an array of the month names.

moment.months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

Month Abbreviations

moment.monthsShort = String[];
Available in version 1.0.0
 

moment.monthsShort should be an array of the month abbreviations.

moment.monthsShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

Weekday Names

moment.weekdays = String[];
Available in version 1.0.0
 

moment.weekdays should be an array of the weekdays names.

moment.weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

Weekday Abbreviations

moment.weekdaysShort = String[];
Available in version 1.0.0
 

moment.weekdaysShort should be an array of the weekdays abbreviations.

moment.weekdaysShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

Long Date Formats

moment.longDateFormat = Object;
Available in version 1.1.0
 

moment.longDateFormat should be an object containing a key/value pair for each long date format (L, LL, LLL, LLLL, and LT). LT should be the time format, and is also used for moment.fn.calendar.

moment.longDateFormat = { 

    LT: "h:mm A",
    L: "MM/DD/YYYY",
    LL: "MMMM D YYYY",
    LLL: "MMMM D YYYY LT",
    LLLL: "dddd, MMMM D YYYY LT"
};

Relative Time

moment.relativeTime = Object;
Available in version 1.0.0
 

moment.relativeTime should be an object of the replacement strings for moment.fn.from.

moment.relativeTime = {

    future: "in %s",
    past: "%s ago",
    s: "seconds",
    m: "a minute",
    mm: "%d minutes",
    h: "an hour",
    hh: "%d hours",
    d: "a day",
    dd: "%d days",
    M: "a month",
    MM: "%d months",
    y: "a year",
    yy: "%d years"
};

future refers to the prefix/suffix for future dates, and past refers to the prefix/suffix for past dates. For all others, a single character refers to the singular, and an double character refers to the plural.

If a language requires additional processing for a token, It can set the token as a function with the following signature. The function should return a string.

function(number, withoutSuffix, key, isFuture) {

    return string;
}

The key variable refers to the replacement key in the relativeTime object. (eg. 's', 'm', 'mm', 'h', etc.)

The number variable refers to the number of units for that key. For 'm', the number is the number of minutes, etc.

The withoutSuffix variable will be true if the token will be displayed without a suffix, and false if it will be displayed with a suffix. (The reason for the inverted logic is because the default behavior is to display with the suffix.)

The isFuture parameter will be true if it is going to use the future suffix/prefix and false if it is going to use the past prefix/suffix.

Note: the isFuture parameter was added in version 1.6.0.

AM/PM

moment.meridiem = Function;
Available in version 1.6.0
 

If your language uses 'am/pm', moment.meridiem can be ommitted, as those values are the defaults.

If your language needs any different computation for am/pm, moment.meridiem should be a callback function that returns the correct string based on hour, minute, and upper/lowercase.

 
moment.meridiem = function (hour, minute, isLower) {
    if (hour < 9) {
        return "早上";
    } else if (hour < 11 && minute < 30) {
        return "上午";
    } else if (hour < 13 && minute < 30) {
        return "中午";
    } else if (hour < 18) {
        return "下午";
    } else {
        return "晚上";
    }
};

Note: Before version 1.6.0, moment.meridiem was a map of upper and lowercase versions of am/pm.

moment.meridiem = {

    am : 'am',
    AM : 'AM',
    pm : 'pm',
    PM : 'PM'
};

This has been deprecated. The 1.6.0 callback function syntax is now used instead.

Calendar

moment.calendar = Object;
Available in version 1.3.0
 

moment.calendar should have the following formatting strings.

moment.calendar = {

    lastDay : '[Yesterday at] LT',
    sameDay : '[Today at] LT',
    nextDay : '[Tomorrow at] LT',
    lastWeek : '[last] dddd [at] LT',
    nextWeek : 'dddd [at] LT',
    sameElse : 'L'
};

Ordinal

moment.ordinal = Function;
Available in version 1.0.0
 

moment.ordinal should be a function that returns the ordinal for a given number.

moment.ordinal = function (number) {

    var b = number % 10;
    return (~~ (number % 100 / 10) === 1) ? 'th' : 
        (b === 1) ? 'st' : 
        (b === 2) ? 'nd' : 
        (b === 3) ? 'rd' : 'th';
};

For more information on ordinal numbers, see wikipedia

Durations

Moment.js also has duration objects. Whereas moments are defined as single points in time, durations are defined as a length of time.

Durations do not have a defined beginning and end date. They are contextless.

A duration is more like '2 hours' than 'between 2 and 4 pm today'.

Creating

moment.duration(Number, String);
moment.duration(Number);
moment.duration(Object);
Available in version 1.6.0
 

To create a duration, call moment.duration() with the length of time in milliseconds.

moment.duration(100); // 100 milliseconds

If you want to create a moment with a unit of measurement other than seconds, you can pass the unit of measurement as well.

moment.duration(2, 'seconds');
moment.duration(2, 'minutes');
moment.duration(2, 'hours');
moment.duration(2, 'days');
moment.duration(2, 'weeks');
moment.duration(2, 'months');
moment.duration(2, 'years');

The same shorthand for moment.fn.add works here as well.

KeyShorthand
yearsy
monthsM
weeksw
daysd
hoursh
minutesm
secondss
millisecondsms

Much like moment.fn.add, you can pass an object of values if you need multiple different units of measurement.

moment.duration({
    seconds: 2,
    minutes: 2,
    hours: 2,
    days: 2,
    weeks: 2,
    months: 2,
    years: 2
});

Humanize

moment.duration().humanize();
Available in version 1.6.0
 

Sometimes, you want all the goodness of moment.fn.from but you don't want to have to create two moments, you just want to display a length of time.

Enter moment.duration().humanize().

moment.duration(1, "minutes").humanize(); // a minute
moment.duration(2, "minutes").humanize(); // 2 minutes
moment.duration(24, "hours").humanize();  // a day

By default, the return string is suffixless. If you want a suffix, pass in true as seen below.

moment.duration(1, "minutes").humanize(true); // in a minute

For suffixes before now, pass in a negative number.

moment.duration(-1, "minutes").humanize(true); // a minute ago

Milliseconds

moment.duration().milliseconds();
moment.duration().asMilliseconds();
Available in version 1.6.0
 

To get the number of milliseconds in a duration, use moment.duration().milliseconds().

It will return a number between 0 and 1000.

moment.duration(500).milliseconds(); // 500
moment.duration(1500).milliseconds(); // 500
moment.duration(15000).milliseconds(); // 0

If you want the length of the duration in milliseconds, use moment.duration().asMilliseconds() instead.

moment.duration(500).asMilliseconds(); // 500
moment.duration(1500).asMilliseconds(); // 1500
moment.duration(15000).asMilliseconds(); // 15000

Seconds

moment.duration().seconds();
moment.duration().asSeconds();
Available in version 1.6.0
 

To get the number of seconds in a duration, use moment.duration().seconds().

It will return a number between 0 and 60.

moment.duration(500).seconds(); // 0
moment.duration(1500).seconds(); // 1
moment.duration(15000).seconds(); // 15

If you want the length of the duration in seconds, use moment.duration().asSeconds() instead.

moment.duration(500).asSeconds(); // 0.5
moment.duration(1500).asSeconds(); // 1.5
moment.duration(15000).asSeconds(); // 15

Minutes

moment.duration().minutes();
moment.duration().asMinutes();
Available in version 1.6.0
 

As with the other getters for durations, moment.duration().minutes() gets the minutes (0 - 60).

moment.duration().asMinutes() gets the length of the duration in minutes.

Hours

moment.duration().hours();
moment.duration().asHours();
Available in version 1.6.0
 

As with the other getters for durations, moment.duration().hours() gets the hours (0 - 24).

moment.duration().asHours() gets the length of the duration in hours.

Days

moment.duration().days();
moment.duration().asDays();
Available in version 1.6.0
 

As with the other getters for durations, moment.duration().days() gets the days (0 - 30).

moment.duration().asDays() gets the length of the duration in days.

Months

moment.duration().months();
moment.duration().asMonths();
Available in version 1.6.0
 

As with the other getters for durations, moment.duration().months() gets the months (0 - 12).

moment.duration().asMonths() gets the length of the duration in months.

Note: The length of a duration in months is defined as 30 days.

Years

moment.duration().years();
moment.duration().asYears();
Available in version 1.6.0
 

As with the other getters for durations, moment.duration().years() gets the years.

moment.duration().asYears() gets the length of the duration in years.

Note: The length of a duration in years is defined as 365 days.

Plugins

Some people have made plugins for moment.js that may be useful to you.

strftime

moment().strftime(String);
 

If you are more comfortable working with strftime instead of LDML-like parsing tokens, you can use Ben Oakes' plugin moment-strftime .

It is available on npm.

npm install moment-strftime

The repository is located at github.com/benjaminoakes/moment-strftime

ISO Calendar

moment().isocalendar();
moment.fromIsocalendar(Array);
 

If you are looking for a Python-like isocalendar method, you can use Rocky Meza's plugin

moment-isocalendar

Calling the isocalendar method on a moment will return an array like the following:

[year, week_of_year, day_of_week, minutes_since_midnight]

moment().isocalendar(); // [2012, 8, 5, 870]

You can also reconstruct a moment from a isocalendar array.

moment.fromIsocalendar([2011, 51, 5, 870]).format('LLLL');
// "Friday, December 23 2011 2:30 PM"

It is available on npm.

npm install moment-isocalendar

The repository is located at github.com/fusionbox/moment-isocalendar