Moment.js Documentation

Moment was designed to work both in the browser and in Node.js.

All code should work in both of these environments, and all unit tests are run in both of these environments.

Currently, the following browsers are used for the ci system: Chrome on Windows XP, IE 8, 9, and 10 on Windows 7, IE 11 on Windows 10, latest Firefox on Linux, and latest Safari on OSX 10.8 and 10.11.

If you want to try the sample codes below, just open your browser's console and enter them.

Node.js

edit
npm install moment
var moment = require('moment'); // require
moment().format(); 

Or in ES6 syntax:

import moment from 'moment';
moment().format();

Note: if you want to work with a particular variation of moment timezone, for example using only data from 2012-2022, you will need to import it from the builds directory like so:

import moment from 'moment-timezone/builds/moment-timezone-with-data-2012-2022';

Note: In 2.4.0, the globally exported moment object was deprecated. It will be removed in next major release.

Bower

edit

bower

bower install --save moment

Notable files are moment.js, locale/*.js and min/moment-with-locales.js.

Require.js

edit

We strongly recommend reading this if you plan to use moment with Require.js. Also upgrade to 2.14.0 or above for best experience.

As a start, you might have acquired moment through bower or node_modules or anything else that places moment.js together with a locales directory in a base folder. Then you should use a tool like adapt-pkg-main , or manually -- using packages config .

requirejs.config({
  packages: [{
    name: 'moment',
    // This location is relative to baseUrl. Choose bower_components
    // or node_modules, depending on how moment was installed.
    location: '[bower_components|node_modules]/moment',
    main: 'moment'
  }]
});

With the above setup, you can require the core with moment and de locale with moment/locale/de.

// only needing core
define(['moment'], function (moment) {
    console.log(moment().format('LLLL'));  // 'Friday, June 24, 2016 1:42 AM'
});

// core with single locale
define(['moment', 'moment/locale/de'], function (moment) {
    moment.locale('de');
    console.log(moment().format('LLLL')); // 'Freitag, 24. Juni 2016 01:42'
});

// core with all locales
define(['moment/min/moment-with-locales'], function (moment) {
    moment.locale('de');
    console.log(moment().format('LLLL')); // 'Freitag, 24. Juni 2016 01:42'
});

// async load locale
define(['require', 'moment'], function(require, moment) {
  // Inside some module after the locale is detected. This is the
  // case where the locale is not known before module load time.
  require(['moment/locale/de'], function(localeModule) {
    // here the locale is loaded, but not yet in use
    console.log(moment().format('LLLL'));  // 'Friday, June 24, 2016 1:42 AM'

    moment.locale('de');
    // Use moment now that the locale has been properly set.
    console.log(moment().format('LLLL')); // 'Freitag, 24. Juni 2016 01:42'
  })
});

For more complicated use cases please read excellent explanation by @jrburke .

Moment will still create a moment global, which is useful to plugins and other third-party code. If you wish to squash that global, use the noGlobal option on the module config.

require.config({
    config: {
        moment: {
            noGlobal: true
        }
    }
});

If you don't specify noGlobal then the globally exported moment will print a deprecation warning. From next major release you'll have to export it yourself if you want that behavior.

For version 2.5.x, in case you use other plugins that rely on Moment but are not AMD-compatible you may need to add wrapShim: true to your r.js config.

Note: To allow moment.js plugins to be loaded in requirejs environments, moment is created as a named module. Because of this, moment must be loaded exactly as as "moment", using paths to determine the directory. Requiring moment with a path like "vendor\moment" will return undefined.

Note: From version 2.9.0 moment exports itself as an anonymous module, so if you're using only the core (no locales / plugins), then you don't need config if you put it on a non-standard location.

Browserify

edit
npm install moment
var moment = require('moment');
moment().format();

Note: There is a bug that prevents moment.locale from being loaded.

var moment = require('moment');
moment.locale('cs');
console.log(moment.locale()); // en

Use the workaround below

var moment = require('moment');
require('moment/locale/cs');
console.log(moment.locale()); // cs

In order to include all the locales

var moment = require('moment');
require("moment/min/locales.min");
moment.locale('cs');
console.log(moment.locale()); // cs

Webpack

edit
npm install moment
var moment = require('moment');
moment().format();

Note: By default, webpack bundles all Moment.js locales (in Moment.js 2.18.1, that’s 160 minified KBs). To strip unnecessary locales and bundle only the used ones, add moment-locales-webpack-plugin :

// webpack.config.js
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');

module.exports = {
    plugins: [
        // To strip all locales except “en”
        new MomentLocalesPlugin(),

        // Or: To strip all locales except “en”, “es-us” and “ru”
        // (“en” is built into Moment and can’t be removed)
        new MomentLocalesPlugin({
            localesToKeep: ['es-us', 'ru'],
        }),
    ],
};

There are other resources to optimize Moment.js with webpack, for example this one .

Typescript 2.13.0+

edit

As of version 2.13.0, Moment includes a typescript definition file.

Install via NPM

npm install moment

Import and use in your Typescript file

import moment = require('moment');

let now = moment().format('LLLL');

Note: If you have trouble importing moment

For Typescript 2.x try adding "moduleResolution": "node" in compilerOptions in your tsconfig.json file

For Typescript 1.x try adding "allowSyntheticDefaultImports": true in compilerOptions in your tsconfig.json file and then use the syntax

import moment from 'moment';

Locale Import

To use moment.locale you first need to import the language you are targeting.

import * as moment from 'moment';
import 'moment/locale/pt-br';

console.log(moment.locale()); // en
moment.locale('fr');
console.log(moment.locale()); // fr
moment.locale('pt-br');
console.log(moment.locale()); // pt-br

System.js

edit

To load moment, place it in the path specified by your System.config in the baseURL configuration. Then import it into your page.

<script src="system.js"></script>
<script>
  System.config({
    baseURL: '/app'
  });

  System.import('moment.js');
 </script>

If you need moment to be loaded as global, you can do this with the meta configuration:

System.config({
  meta: {
    'moment': { format: 'global' }
  }
});

Alternatively, to provide Moment as a global to only a specific dependency, you can do this:

System.config({
  meta: {
    'path/to/global-file.js': {
      globals: {
        moment: 'moment'
      }
    }
  }
});

Troubleshooting

edit

If you are having any troubles, the first place to check is the guides .

If you don't find what you are looking for there, try asking a question on Stack Overflow with the momentjs tag.

Note: More than half of the issues seen on Stack Overflow can be answered by this blog post .

You can also use the GitHub issue tracker to find related issues or open a new issue.

In addition, Moment has a Gitter where the internal team is frequently available.

For general troubleshooting help, Stack Overflow is the preferred forum. Moment's maintainers are very active on Stack Overflow, as are several other knowledgeable users. The fastest response will be there.

Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object. To get this wrapper object, simply call moment() with one of the supported input types.

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

For ease of reference, any method on the Moment.prototype will be referenced in the docs as moment#method. So Moment.prototype.format == moment.fn.format == moment#format.

Please read:

  • moment(...) is local mode. Ambiguous input (without offset) is assumed to be local time. Unambiguous input (with offset) is adjusted to local time.
  • moment.utc(...) is utc mode. Ambiguous input is assumed to be UTC. Unambiguous input is adjusted to UTC.
  • moment.parseZone() keep the input zone passed in. If the input is ambiguous, it is the same as local mode.
  • moment.tz(...) with the moment-timezone plugin can parse input in a specific time zone.

Keep in mind that a time zone and a time zone offset are two different things. An offset of -08:00 doesn't necessarily mean you are in the US Pacific time zone.

See the Parsing Guide for additional information .

Now 1.0.0+

edit
moment();
moment(undefined);
// From 2.14.0 onward, also supported
moment([]);
moment({});

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()).

Note: From version 2.14.0, moment([]) and moment({}) also return now. They used to default to start-of-today before 2.14.0, but that was arbitrary so it was changed.

Note: Function parameters default to undefined when not passed in. Moment treats moment(undefined) as moment().

var x = undefined;
moment(x).isSame(moment(), 'second'); // true

String 1.0.0+

edit
moment(String);

When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.

var day = moment("1995-12-25");

Warning: Browser support for parsing strings is inconsistent . Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

Supported ISO 8601 strings

An ISO 8601 string requires a date part.

2013-02-08  # A calendar date part
2013-02     # A month date part
2013-W06-5  # A week date part
2013-039    # An ordinal date part

20130208    # Basic (short) full date
201303      # Basic (short) year+month
2013        # Basic (short) year only
2013W065    # Basic (short) week, weekday
2013W06     # Basic (short) week only
2013050     # Basic (short) ordinal date (year + day-of-year)

A time part can also be included, separated from the date part by a space or an uppercase T.

2013-02-08T09            # An hour time part separated by a T
2013-02-08 09            # An hour time part separated by a space
2013-02-08 09:30         # An hour and minute time part
2013-02-08 09:30:26      # An hour, minute, and second time part
2013-02-08 09:30:26.123  # An hour, minute, second, and millisecond time part
2013-02-08 24:00:00.000  # hour 24, minute, second, millisecond equal 0 means next day at midnight

20130208T080910,123      # Short date and time up to ms, separated by comma
20130208T080910.123      # Short date and time up to ms
20130208T080910          # Short date and time up to seconds
20130208T0809            # Short date and time up to minutes
20130208T08              # Short date and time, hours only

Any of the date parts can have a time part.

2013-02-08 09  # A calendar date part and hour time part
2013-W06-5 09  # A week date part and hour time part
2013-039 09    # An ordinal date part and hour time part

If a time part is included, an offset from UTC can also be included as +-HH:mm, +-HHmm, +-HH or Z.

2013-02-08 09+07:00            # +-HH:mm
2013-02-08 09-0100             # +-HHmm
2013-02-08 09Z                 # Z
2013-02-08 09:30:26.123+07:00  # +-HH:mm
2013-02-08 09:30:26.123+07     # +-HH

Note: Support for the week and ordinal formats was added in version 2.3.0.

If a string does not match any of the above formats and is not able to be parsed with Date.parse, moment#isValid will return false.

moment("not a real date").isValid(); // false

The RFC 2822 date time format

Before parsing a RFC 2822 date time the string is cleansed to remove any comments and/or newline characters. The additional characters are legal in the format but add nothing to creating a valid moment instance.

After cleansing, the string is validated in the following space-separated sections, all using the English language:

6 Mar 17 21:22 UT
6 Mar 17 21:22:23 UT
6 Mar 2017 21:22:23 GMT
06 Mar 2017 21:22:23 Z
Mon 06 Mar 2017 21:22:23 z
Mon, 06 Mar 2017 21:22:23 +0000
  1. Day of Week in three letters, followed by an optional comma. (optional)
  2. Day of Month (1 or 2 digit), followed by a three-letter month and 2 or 4 digit year
  3. Two-digit hours and minutes separated by a colon (:), followed optionally by another colon and seconds in 2-digits
  4. Timezone or offset in one of the following formats:
  5. UT : +0000
  6. GMT : +0000
  7. EST | CST | MST | PST | EDT | CDT | MDT | PDT : US time zones*
  8. A - I | K - Z : Military time zones*
  9. Time offset +/-9999

[*] See section 4.3 of the specification for details.

The parser also confirms that the day-of-week (when included) is consistent with the date.

String + Format 1.0.0+

edit
moment(String, String);
moment(String, String, String);
moment(String, String, String[]);
moment(String, String, Boolean);
moment(String, String, String, Boolean);

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

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

The parser ignores non-alphanumeric characters by default, so both of the following will return the same thing.

moment("12-25-1995", "MM-DD-YYYY");
moment("12/25/1995", "MM-DD-YYYY");

You may get unexpected results when parsing both date and time. The below example may not parse as you expect:

moment('24/12/2019 09:15:00', "DD MM YYYY hh:mm:ss");

You can use strict mode, which will identify the parsing error and set the Moment object as invalid:

moment('24/12/2019 09:15:00', "DD MM YYYY hh:mm:ss", true);

The parsing tokens are similar to the formatting tokens used in moment#format.

Year, month, and day tokens

Tokens are case-sensitive.

Input Example Description
YYYY 2014 4 or 2 digit year. Note: Only 4 digit can be parsed on strict mode
YY 14 2 digit year
Y -25 Year with any number of digits and sign
Q 1..4 Quarter of year. Sets month to first month in quarter.
M MM 1..12 Month number
MMM MMMM Jan..December Month name in locale set by moment.locale()
D DD 1..31 Day of month
Do 1st..31st Day of month with ordinal
DDD DDDD 1..365 Day of year
X 1410715640.579 Unix timestamp
x 1410715640579 Unix ms timestamp

YYYY from version 2.10.5 supports 2 digit years, and converts them to a year near 2000 (same as YY).

Y was added in 2.11.1. It will match any number, signed or unsigned. It is useful for years that are not 4 digits or are before the common era. It can be used for any year.

Week year, week, and weekday tokens

For these, the lowercase tokens use the locale aware week start days, and the uppercase tokens use the ISO week date start days.

Tokens are case-sensitive.

Input Example Description
gggg 2014 Locale 4 digit week year
gg 14 Locale 2 digit week year
w ww 1..53 Locale week of year
e 0..6 Locale day of week
ddd dddd Mon...Sunday Day name in locale set by moment.locale()
GGGG 2014 ISO 4 digit week year
GG 14 ISO 2 digit week year
W WW 1..53 ISO week of year
E 1..7 ISO day of week

Locale aware formats

Locale aware date and time formats are also available using LT LTS L LL LLL LLLL. They were added in version 2.2.1, except LTS which was added 2.8.4.

Tokens are case-sensitive.

Input Example Description
L 04/09/1986 Date (in local format)
LL September 4 1986 Month name, day of month, year
LLL September 4 1986 8:30 PM Month name, day of month, year, time
LLLL Thursday, September 4 1986 8:30 PM Day of week, month name, day of month, year, time
LT 8:30 PM Time (without seconds)
LTS 8:30:00 PM Time (with seconds)

Hour, minute, second, millisecond, and offset tokens

Tokens are case-sensitive.

Input Example Description
H HH 0..23 Hours (24 hour time)
h hh 1..12 Hours (12 hour time used with a A.)
k kk 1..24 Hours (24 hour time from 1 to 24)
a A am pm Post or ante meridiem (Note the one character a p are also considered valid)
m mm 0..59 Minutes
s ss 0..59 Seconds
S SS SSS ... SSSSSSSSS 0..999999999 Fractional seconds
Z ZZ +12:00 Offset from UTC as +-HH:mm, +-HHmm, or Z

From version 2.10.5: fractional second tokens length 4 up to 9 can parse any number of digits, but will only consider the top 3 (milliseconds). Use if you have the time printed with many fractional digits and want to consume the input.

Note that the number of S characters provided is only relevant when parsing in strict mode. In standard mode, S, SS, SSS, SSSS are all equivalent, and interpreted as fractions of a second. For example, .12 is always 120 milliseconds, passing SS will not cause it to be interpreted as 12 milliseconds.

Z ZZ were added in version 1.2.0.

S SS SSS were added in version 1.6.0.

X was added in version 2.0.0.

SSSSS ... SSSSSSSSS were added in version 2.10.5.

k kk were added in version 2.13.0.

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

moment("2010-10-20 4:30",       "YYYY-MM-DD HH:mm");   // parsed as 4:30 local time
moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z"); // parsed as 4:30 UTC

Tokens are case-sensitive.

Input Examples Description
y .. yyyy 5 +5 -500 Years
yo 5th 1st Ordinal Years
N AD Abbr Era name
NN AD Short Era name
NNN Anno Domini Full Era name

Era support was added in 2.25.0. The tokens/API are still in flux.

Notes and gotchas

If the moment that results from the parsed input does not exist, moment#isValid will return false.

moment("2010 13",           "YYYY MM").isValid();     // false (not a real month)
moment("2010 11 31",        "YYYY MM DD").isValid();  // false (not a real day)
moment("2010 2 29",         "YYYY MM DD").isValid();  // false (not a leap year)
moment("2010 notamonth 29", "YYYY MMM DD").isValid(); // false (not a real month name)

As of version 2.0.0, a locale key can be passed as the third parameter to moment() and moment.utc().

moment('2012 juillet', 'YYYY MMM', 'fr');
moment('2012 July',    'YYYY MMM', 'en');
moment('2012 July',    'YYYY MMM', ['qj', 'en']);

Moment's parser is very forgiving, and this can lead to undesired/unexpected behavior.

For example, the following behavior can be observed:

moment('2016 is a date', 'YYYY-MM-DD').isValid() //true, 2016 was matched

Previous to 2.13.0 the parser exhibited the following behavior. This has been corrected.

moment('I am spartacus', 'h:hh A').isValid();     //true - the 'am' matches the 'A' flag.

As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly, including delimeters.

moment('It is 2012-05-25', 'YYYY-MM-DD').isValid();       // true
moment('It is 2012-05-25', 'YYYY-MM-DD', true).isValid(); // false
moment('2012-05-25',       'YYYY-MM-DD', true).isValid(); // true
moment('2012.05.25',       'YYYY-MM-DD', true).isValid(); // false

You can use both locale and strictness.

moment('2012-10-14', 'YYYY-MM-DD', 'fr', true);

Strict parsing is frequently the best parsing option. For more information about choosing strict vs forgiving parsing, see the parsing guide.

Parsing two digit years

By default, two digit years above 68 are assumed to be in the 1900's and years 68 or below are assumed to be in the 2000's. This can be changed by replacing the moment.parseTwoDigitYear method. The only argument of this method is a string containing the two years input by the user, and should return the year as an integer.

moment.parseTwoDigitYear = function(yearString) {
    return parseInt(yearString) + 2000;
}

Parsing glued hour and minutes

From version 2.11.0 parsing hmm, Hmm, hmmss and Hmmss is supported:

moment("123", "hmm").format("HH:mm") === "01:23"
moment("1234", "hmm").format("HH:mm") === "12:34"

String + Formats 1.0.0+

edit
moment(String, String[], String, Boolean);

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.

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

Starting in version 2.3.0, Moment uses some simple heuristics to determine which format to use. In order:

  • Prefer formats resulting in valid dates over invalid ones.
  • Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.
  • Prefer formats earlier in the array than later.
moment("29-06-1995", ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"]); // uses the last format
moment("05-06-1995", ["MM-DD-YYYY", "DD-MM-YYYY"]);          // uses the first format

You may also specify a locale and strictness argument. They work the same as the single format case.

moment("29-06-1995", ["MM-DD-YYYY", "DD-MM-YYYY"], 'fr');       // uses 'fr' locale
moment("29-06-1995", ["MM-DD-YYYY", "DD-MM-YYYY"], true);       // uses strict parsing
moment("05-06-1995", ["MM-DD-YYYY", "DD-MM-YYYY"], 'fr', true); // uses 'fr' locale and strict parsing

Note: Parsing multiple formats is considerably slower than parsing a single format. If you can avoid it, it is much faster to parse a single format.

Special Formats 2.7.0+

edit
moment(String, moment.CUSTOM_FORMAT, [String], [Boolean]);
moment(String, moment.HTML5_FMT.DATETIME_LOCAL, [String], [Boolean]); // from 2.20.0
moment(String, [..., moment.ISO_8601, ...], [String], [Boolean]);

ISO-8601 is a standard for time and duration display. Moment already supports parsing iso-8601 strings, but this can be specified explicitly in the format/list of formats when constructing a moment.

To specify iso-8601 parsing use moment.ISO_8601 constant.

moment("2010-01-01T05:06:07", moment.ISO_8601);
moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);

As of version 2.20.0, the following HTML5 formats are available as constants in the moment object's HTML5_FMT property (moment.HTML5_FMT.*):

Constant Format Example Input Type
DATETIME_LOCAL YYYY-MM-DDTHH:mm 2017-12-14T16:34 <input type="datetime-local" />
DATETIME_LOCAL_SECONDS YYYY-MM-DDTHH:mm:ss 2017-12-14T16:34:10 <input type="datetime-local" step="1" />
DATETIME_LOCAL_MS YYYY-MM-DDTHH:mm:ss.SSS 2017-12-14T16:34:10.234 <input type="datetime-local" step="0.001" />
DATE YYYY-MM-DD 2017-12-14 <input type="date" />
TIME HH:mm 16:34 <input type="time" />
TIME_SECONDS HH:mm:ss 16:34:10 <input type="time" step="1" />
TIME_MS HH:mm:ss.SSS 16:34:10.234 <input type="time" step="0.001" />
WEEK GGGG-[W]WW 2017-W50 <input type="week" />
MONTH YYYY-MM 2017-12 <input type="month" />

Object 2.2.1+

edit
moment({unit: value, ...});
moment({ hour:15, minute:10 });
moment({ y    :2010, M     :3, d   :5, h    :15, m      :10, s      :3, ms          :123});
moment({ year :2010, month :3, day :5, hour :15, minute :10, second :3, millisecond :123});
moment({ years:2010, months:3, days:5, hours:15, minutes:10, seconds:3, milliseconds:123});
moment({ years:2010, months:3, date:5, hours:15, minutes:10, seconds:3, milliseconds:123});
moment({ years:'2010', months:'3', date:'5', hours:'15', minutes:'10', seconds:'3', milliseconds:'123'});  // from 2.11.0

You can create a moment by specifying some of the units in an object.

Omitted units default to 0 or the current date, month, and year.

day and date key both mean day-of-the-month.

date was added in 2.8.4.

String values (as shown on the last line) are supported from version 2.11.0.

Note that like moment(Array) and new Date(year, month, date), months are 0 indexed.

Unix Timestamp (seconds) 1.6.0+

edit
moment.unix(Number)

To create a moment from a Unix timestamp (seconds since the Unix Epoch), use moment.unix(Number).

var day = moment.unix(1318781876);

This is implemented as moment(timestamp * 1000), so partial seconds in the input timestamp are included.

var day = moment.unix(1318781876.721);

Note: Despite Unix timestamps being UTC-based, this function creates a moment object in local mode. If you need UTC, then subsequently call .utc(), as in:

var day = moment.unix(1318781876).utc();

Date 1.0.0+

edit
moment(Date);

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

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

This clones the Date object; further changes to the Date won't affect the Moment, and vice-versa.

Array 1.0.0+

edit
moment(Number[]);

You can create a moment with an array of numbers that mirror the parameters passed to new Date()

[year, month, day, hour, minute, second, millisecond]

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.

moment([2010]);        // January 1st
moment([2010, 6]);     // July 1st
moment([2010, 6, 10]); // July 10th

Construction with an array will create a date in the current time zone. To create a date from an array at UTC, use moment.utc(Number[]).

moment.utc([2010, 1, 14, 15, 25, 50, 125]);

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

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

If the date represented by the array does not exist, moment#isValid will return false.

moment([2010, 12]).isValid();     // false (not a real month)
moment([2010, 10, 31]).isValid(); // false (not a real day)
moment([2010, 1, 29]).isValid();  // false (not a leap year)

ASP.NET JSON Date 1.3.0+

edit
moment(String);

Microsoft Web API returns JSON dates in proper ISO-8601 format by default, but older ASP.NET technologies may return dates in JSON as /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)/"); // 2007-12-28T23:11:57.056-07:00

Moment Clone 1.2.0+

edit
moment(Moment);

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

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#clone to clone a moment.

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

UTC 1.5.0+

edit
moment.utc();
moment.utc(Number);
moment.utc(Number[]);
moment.utc(String);
moment.utc(String, String);
moment.utc(String, String[]);
moment.utc(String, String, String);
moment.utc(String, String, String[]);
moment.utc(String, String, Boolean);
moment.utc(String, String, String, Boolean);
moment.utc(Moment);
moment.utc(Date);

By default, moment parses and displays in local time.

If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment().

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.

moment().format();     // 2013-02-04T10:35:24-08:00
moment.utc().format(); // 2013-02-04T18:35:24+00:00

Additionally, while in UTC mode, all getters and setters will internally use the Date#getUTC* and Date#setUTC* methods instead of the Date#get* and Date#set* methods.

moment.utc().seconds(30).valueOf() === new Date().setUTCSeconds(30);
moment.utc().seconds()   === new Date().getUTCSeconds();

It is important to note that though the displays differ above, they are both the same moment in time.

var a = moment();
var b = moment.utc();
a.format();  // 2013-02-04T10:35:24-08:00
b.format();  // 2013-02-04T18:35:24+00:00
a.valueOf(); // 1360002924000
b.valueOf(); // 1360002924000

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

To switch from UTC to local time, you can use moment#utc or moment#local.

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

parseZone 2.3.0+

edit
moment.parseZone()
moment.parseZone(String)
moment.parseZone(String, String)
moment.parseZone(String, [String])
moment.parseZone(String, String, Boolean)
moment.parseZone(String, String, String, Boolean)

Moment's string parsing functions like moment(string) and moment.utc(string) accept offset information if provided, but convert the resulting Moment object to local or UTC time. In contrast, moment.parseZone() parses the string but keeps the resulting Moment object in a fixed-offset timezone with the provided offset in the string.

moment.parseZone("2013-01-01T00:00:00-13:00").utcOffset(); // -780 ("-13:00" in total minutes)
moment.parseZone('2013 01 01 05 -13:00', 'YYYY MM DD HH ZZ').utcOffset(); // -780  ("-13:00" in total minutes)
moment.parseZone('2013-01-01-13:00', ['DD MM YYYY ZZ', 'YYYY MM DD ZZ']).utcOffset(); // -780  ("-13:00" in total minutes);

It also allows you to pass locale and strictness arguments.

moment.parseZone("2013 01 01 -13:00", 'YYYY MM DD ZZ', true).utcOffset(); // -780  ("-13:00" in total minutes)
moment.parseZone("2013-01-01-13:00", 'YYYY MM DD ZZ', true).utcOffset(); // NaN (doesn't pass the strictness check)
moment.parseZone("2013 01 01 -13:00", 'YYYY MM DD ZZ', 'fr', true).utcOffset(); // -780 (with locale and strictness argument)
moment.parseZone("2013 01 01 -13:00", ['DD MM YYYY ZZ', 'YYYY MM DD ZZ'], 'fr', true).utcOffset(); // -780 (with locale and strictness argument alongside an array of formats)

moment.parseZone is equivalent to parsing the string and using moment#utcOffset to parse the zone.

var s = "2013-01-01T00:00:00-13:00";
moment(s).utcOffset(s);

Validation 1.7.0+

edit
moment().isValid();

Moment applies stricter initialization rules than the Date constructor.

new Date(2013, 25, 14).toString(); // "Sat Feb 14 2015 00:00:00 GMT-0500 (EST)"
moment([2015, 25, 35]).format();   // 'Invalid date'

You can check whether the Moment considers the date invalid using moment#isValid. You can check the metrics used by #isValid using moment#parsingFlags, which returns an object.

The following parsing flags result in an invalid date:

  • overflow: An overflow of a date field, such as a 13th month, a 32nd day of the month (or a 29th of February on non-leap years), a 367th day of the year, etc. overflow contains the index of the invalid unit to match #invalidAt (see below); -1 means no overflow.
  • invalidMonth: An invalid month name, such as moment('Marbruary', 'MMMM');. Contains the invalid month string itself, or else null.
  • empty: An input string that contains nothing parsable, such as moment('this is nonsense');. Boolean.
  • nullInput: A null input, like moment(null);. Boolean.
  • invalidFormat: An empty list of formats, such as moment('2013-05-25', []). Boolean.
  • userInvalidated: A date created explicitly as invalid, such as moment.invalid(). Boolean.

In addition to the above, As of 2.13.0 the meridiem and parsedDateParts flags work together to determine date validity.

  • meridiem: Indicates what meridiem (AM/PM) was parsed, if any. String.
  • parsedDateParts: Returns an array of date parts parsed in descending order - i.e. parsedDateParts[0] === year. If no parts are present, but meridiem has value, date is invalid. Array.

Additionally, if the Moment is parsed in strict mode, these flags must be empty for the Moment to be valid:

  • unusedTokens: array of format substrings not found in the input string
  • unusedInput: array of input substrings not matched to the format string

Note: Moment's concept of validity became more strict and consistent between 2.2 and 2.3. Note: Validity is determined on moment creation. A modified moment (i.e. moment().hour(NaN)) will remain valid.

Additionally, you can use moment#invalidAt to determine which date unit overflowed.

var m = moment("2011-10-10T10:20:90");
m.isValid(); // false
m.invalidAt(); // 5 for seconds

The return value has the following meaning:

  1. years
  2. months
  3. days
  4. hours
  5. minutes
  6. seconds
  7. milliseconds

Note: In case of multiple wrong units the first one is returned (because days validity may depend on month, for example).

Invalid Moments

If a moment is invalid, it behaves like a NaN in floating point operations.

All of the following produce invalid moments:

  • invalid.add(unit, value)
  • another.add(invalid)
  • invalid.clone()
  • invalid.diff(another)
  • invalid.endOf(unit)
  • invalid.max(another)
  • another.max(invalid)
  • invalid.min(another)
  • another.min(invalid)
  • invalid.set(unit, value)
  • invalid.startOf(unit)
  • invalid.subtract(unit, value)

The following produce a localized version of 'InvalidDate':

  • invalid.format(anyFmt) results in 'Invalid Date' in the current locale
  • invalid.from(another)
  • another.from(invalid)
  • invalid.fromNow(suffix)
  • invalid.to(another)
  • another.to(invalid)
  • invalid.toNow(suffix)
  • invalid.toISOString() (Before 2.18.0)
  • invalid.toString()

The following return false:

  • invalid.isAfter(another)
  • invalid.isAfter(invalid)
  • another.isAfter(invalid)
  • invalid.isBefore(another)
  • invalid.isBefore(invalid)
  • another.isBefore(invalid)
  • invalid.isBetween(another, another)
  • invalid.isBetween(invalid, invalid)
  • invalid.isSame(another)
  • invalid.isSame(invalid)
  • another.isSame(invalid)
  • invalid.isSameOrAfter(another)
  • invalid.isSameOrAfter(invalid)
  • another.isSameOrAfter(invalid)
  • invalid.isSameOrBefore(another)
  • invalid.isSameOrBefore(invalid)
  • another.isSameOrBefore(invalid)

And these return null or NaN with some structure:

  • invalid.get(unit) returns null, as all other named getters
  • invalid.toArray() === [NaN, NaN, NaN, NaN, NaN, NaN]
  • invalid.toObject() has all values set to NaN
  • invalid.toDate() returns an invalid Date object
  • invalid.toJSON() returns null
  • invalid.unix() returns null
  • invalid.valueOf() returns null
  • invalid.toISOString() returns null (As of 2.18.0)

Creation Data 2.11.0+

edit
moment().creationData();

After a moment object is created, all of the inputs can be accessed with creationData() method:

moment("2013-01-02", "YYYY-MM-DD", true).creationData() === {
    input: "2013-01-02",
    format: "YYYY-MM-DD",
    locale: Locale obj,
    isUTC: false,
    strict: true
}

Defaults 2.2.1+

edit
moment("15", "hh")

You can create a moment object specifying only some of the units, and the rest will be defaulted to the current day, month or year, or 0 for hours, minutes, seconds and milliseconds.

Defaulting to now, when nothing is passed:

moment();  // current date and time

Defaulting to today, when only hours, minutes, seconds and milliseconds are passed:

moment(5, "HH");  // today, 5:00:00.000
moment({hour: 5});  // today, 5:00:00.000
moment({hour: 5, minute: 10});  // today, 5:10.00.000
moment({hour: 5, minute: 10, seconds: 20});  // today, 5:10.20.000
moment({hour: 5, minute: 10, seconds: 20, milliseconds: 300});  // today, 5:10.20.300

Defaulting to this month and year, when only days and smaller units are passed:

moment(5, "DD");  // this month, 5th day-of-month
moment("4 05:06:07", "DD hh:mm:ss");  // this month, 4th day-of-month, 05:06:07.000

Defaulting to this year, if year is not specified:

moment(3, "MM");  // this year, 3rd month (March)
moment("Apr 4 05:06:07", "MMM DD hh:mm:ss");  // this year, 4th April, 05:06:07.000

Moment.js uses overloaded getters and setters. You may be familiar with this pattern from its use in jQuery.

Calling these methods without parameters acts as a getter, and calling them with a parameter acts as a setter.

These map to the corresponding function on the native Date object.

moment().seconds(30).valueOf() === new Date().setSeconds(30);
moment().seconds()   === new Date().getSeconds();

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

moment.utc().seconds(30).valueOf() === new Date().setUTCSeconds(30);
moment.utc().seconds()   === new Date().getUTCSeconds();

For convenience, both singular and plural method names exist as of version 2.0.0.

Note: All of these methods mutate the original moment when used as setters.

Note: From 2.19.0 passing NaN to any setter is a no-op. Before 2.19.0 it was invalidating the moment in a wrong way.

Millisecond 1.3.0+

edit
moment().millisecond(Number);
moment().millisecond(); // Number
moment().milliseconds(Number);
moment().milliseconds(); // Number

Gets or sets the milliseconds.

Accepts numbers from 0 to 999. If the range is exceeded, it will bubble up to the seconds.

Second 1.0.0+

edit
moment().second(Number);
moment().second(); // Number
moment().seconds(Number);
moment().seconds(); // Number

Gets or sets the seconds.

Accepts numbers from 0 to 59. If the range is exceeded, it will bubble up to the minutes.

Minute 1.0.0+

edit
moment().minute(Number);
moment().minute(); // Number
moment().minutes(Number);
moment().minutes(); // Number

Gets or sets the minutes.

Accepts numbers from 0 to 59. If the range is exceeded, it will bubble up to the hour.

Hour 1.0.0+

edit
moment().hour(Number);
moment().hour(); // Number
moment().hours(Number);
moment().hours(); // Number

Gets or sets the hour.

Accepts numbers from 0 to 23. If the range is exceeded, it will bubble up to the day.

Date of Month 1.0.0+

edit
moment().date(Number);
moment().date(); // Number
moment().dates(Number);
moment().dates(); // Number

Gets or sets the day of the month.

Accepts numbers from 1 to 31. If the range is exceeded, it will bubble up to the months.

Note: Moment#date is for the date of the month, and Moment#day is for the day of the week.

Note: if you chain multiple actions to construct a date, you should start from a year, then a month, then a day etc. Otherwise you may get unexpected results, like when day=31 and current month has only 30 days (the same applies to native JavaScript Date manipulation), the returned date will be the 30th of the current month (see month for more details).

Bad: moment().date(day).month(month).year(year)

Good: moment().year(year).month(month).date(day)

2.16.0 deprecated using moment().dates(). Use moment().date() instead.

Day of Week 1.3.0+

edit
moment().day(Number|String);
moment().day(); // Number
moment().days(Number|String);
moment().days(); // Number

Gets or sets the day of the week.

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

If the value given is from 0 to 6, the resulting date will be within the current (Sunday-to-Saturday) week.

If the range is exceeded, it will bubble up to other weeks.

moment().day(-7); // last Sunday (0 - 7)
moment().day(0); // this Sunday (0)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)

Note: Moment#date is for the date of the month, and Moment#day is for the day of the week.

As of 2.1.0, a day name is also supported. This is parsed in the moment's current locale.

moment().day("Sunday");
moment().day("Monday");

Day of Week (Locale Aware) 2.1.0+

edit
moment().weekday(Number);
moment().weekday(); // Number

Gets or sets the day of the week according to the locale.

If the locale assigns Monday as the first day of the week, moment().weekday(0) will be Monday. If Sunday is the first day of the week, moment().weekday(0) will be Sunday.

As with moment#day, if the range is exceeded, it will bubble up to other weeks.

// when Monday is the first day of the week
moment().weekday(-7); // last Monday
moment().weekday(7); // next Monday
// when Sunday is the first day of the week
moment().weekday(-7); // last Sunday
moment().weekday(7); // next Sunday

ISO Day of Week 2.1.0+

edit
moment().isoWeekday(Number);
moment().isoWeekday(); // Number

Gets or sets the ISO day of the week with 1 being Monday and 7 being Sunday.

As with moment#day, if the range is exceeded, it will bubble up to other weeks.

moment().isoWeekday(1); // Monday
moment().isoWeekday(7); // Sunday

A day name is also supported. This is parsed in the moment's current locale.

moment().isoWeekday("Sunday");
moment().isoWeekday("Monday");

Day of Year 2.0.0+

edit
moment().dayOfYear(Number);
moment().dayOfYear(); // Number

Gets or sets the day of the year.

Accepts numbers from 1 to 366. If the range is exceeded, it will bubble up to the years.

Week of Year 2.0.0+

edit
moment().week(Number);
moment().week(); // Number
moment().weeks(Number);
moment().weeks(); // Number

Gets or sets the week of the year.

Because different locales define week of year numbering differently, Moment.js added moment#week to get/set the localized week of the year.

The week of the year varies depending on which day is the first day of the week (Sunday, Monday, etc), and which week is the first week of the year.

For example, in the United States, Sunday is the first day of the week. The week with January 1st in it is the first week of the year.

In France, Monday is the first day of the week, and the week with January 4th is the first week of the year.

The output of moment#week will depend on the locale for that moment.

When setting the week of the year, the day of the week is retained.

Week of Year (ISO) 2.0.0+

edit
moment().isoWeek(Number);
moment().isoWeek(); // Number
moment().isoWeeks(Number);
moment().isoWeeks(); // Number

Gets or sets the ISO week of the year .

When setting the week of the year, the day of the week is retained.

Month 1.0.0+

edit
moment().month(Number|String);
moment().month(); // Number
moment().months(Number|String);
moment().months(); // Number

Gets or sets the month.

Accepts numbers from 0 to 11. If the range is exceeded, it will bubble up to the year.

Note: Months are zero indexed, so January is month 0.

As of 2.1.0, a month name is also supported. This is parsed in the moment's current locale.

moment().month("January");
moment().month("Feb");

Before version 2.1.0, if a moment changed months and the new month did not have enough days to keep the current day of month, it would overflow to the next month.

As of version 2.1.0, this was changed to be clamped to the end of the target month.

// before 2.1.0
moment([2012, 0, 31]).month(1).format("YYYY-MM-DD"); // 2012-03-02
// after 2.1.0
moment([2012, 0, 31]).month(1).format("YYYY-MM-DD"); // 2012-02-29

2.16.0 deprecated using moment().months(). Use moment().month() instead.

Quarter 2.6.0+

edit
moment().quarter(); // Number
moment().quarter(Number);
moment().quarters(); // Number
moment().quarters(Number);

Gets the quarter (1 to 4).

moment('2013-01-01T00:00:00.000').quarter() // 1
moment('2013-04-01T00:00:00.000').subtract(1, 'ms').quarter() // 1
moment('2013-04-01T00:00:00.000').quarter() // 2
moment('2013-07-01T00:00:00.000').subtract(1, 'ms').quarter() // 2
moment('2013-07-01T00:00:00.000').quarter() // 3
moment('2013-10-01T00:00:00.000').subtract(1, 'ms').quarter() // 3
moment('2013-10-01T00:00:00.000').quarter() // 4
moment('2014-01-01T00:00:00.000').subtract(1, 'ms').quarter() // 4

Sets the quarter (1 to 4).

moment('2013-01-01T00:00:00.000').quarter(2) // '2013-04-01T00:00:00.000'
moment('2013-02-05T05:06:07.000').quarter(2).format() // '2013-05-05T05:06:07-07:00'

Year 1.0.0+

edit
moment().year(Number);
moment().year(); // Number
moment().years(Number);
moment().years(); // Number

Gets or sets the year.

Accepts numbers from -270,000 to 270,000.

2.6.0 deprecated using moment().years(). Use moment().year() instead.

Week Year 2.1.0+

edit
moment().weekYear(Number);
moment().weekYear(); // Number

Gets or sets the week-year according to the locale.

Because the first day of the first week does not always fall on the first day of the year, sometimes the week-year will differ from the month year.

For example, in the US, the week that contains Jan 1 is always the first week. In the US, weeks also start on Sunday. If Jan 1 was a Monday, Dec 31 would belong to the same week as Jan 1, and thus the same week-year as Jan 1. Dec 30 would have a different week-year than Dec 31.

Weeks In Year 2.6.0+

edit
moment().weeksInYear();

Gets the number of weeks according to locale in the current moment's year.

Get 2.2.1+

edit
moment().get('year');
moment().get('month');  // 0 to 11
moment().get('date');
moment().get('hour');
moment().get('minute');
moment().get('second');
moment().get('millisecond');

String getter. In general

moment().get(unit) === moment()[unit]()

Units are case insensitive, and support plural and short forms: year (years, y), month (months, M), date (dates, D), hour (hours, h), minute (minutes, m), second (seconds, s), millisecond (milliseconds, ms).

Set 2.2.1+

edit
moment().set(String, Int);
moment().set(Object(String, Int));

Generic setter, accepting unit as first argument, and value as second:

moment().set('year', 2013);
moment().set('month', 3);  // April
moment().set('date', 1);
moment().set('hour', 13);
moment().set('minute', 20);
moment().set('second', 30);
moment().set('millisecond', 123);

moment().set({'year': 2013, 'month': 3});

Units are case insensitive, and support plural and short forms: year (years, y), month (months, M), date (dates, D), hour (hours, h), minute (minutes, m), second (seconds, s), millisecond (milliseconds, ms).

Object parsing was added in 2.9.0

Maximum 2.7.0+

edit
moment.max(Moment[,Moment...]);
moment.max(Moment[]);

Returns the maximum (most distant future) of the given moment instances.

For example:

var a = moment().subtract(1, 'day');
var b = moment().add(1, 'day');
moment.max(a, b);  // b

var friends = fetchFriends(); /* [{name: 'Dan', birthday: '11.12.1977'}, {name: 'Mary', birthday: '11.12.1986'}, {name: 'Stephan', birthday: '11.01.1993'}]*/
var friendsBirthDays = friends.map(function(friend){
    return moment(friend.birthday, 'DD.MM.YYYY');
});
moment.max(friendsBirthDays);  // '11.01.1993'

With no arguments the function returns a moment instance with the current time.

From version 2.10.5, if an invalid moment is one of the arguments, the result is an invalid moment.

moment.max(moment(), moment.invalid()).isValid() === false
moment.max(moment.invalid(), moment()).isValid() === false
moment.max([moment(), moment.invalid()]).isValid() === false
moment.max([moment.invalid(), moment()]).isValid() === false

Minimum 2.7.0+

edit
moment.min(Moment[,Moment...]);
moment.min(Moment[]);

Returns the minimum (most distant past) of the given moment instances.

For example:

var a = moment().subtract(1, 'day');
var b = moment().add(1, 'day');
moment.min(a, b);  // a
moment.min([a, b]); // a

With no arguments the function returns a moment instance with the current time.

From version 2.10.5, if an invalid moment is one of the arguments, the result is an invalid moment.

moment.min(moment(), moment.invalid()).isValid() === false
moment.min(moment.invalid(), moment()).isValid() === false
moment.min([moment(), moment.invalid()]).isValid() === false
moment.min([moment.invalid(), moment()]).isValid() === false

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

Moment.js uses the fluent interface pattern , also known as method chaining . This allows you to do crazy things like the following.

moment().add(7, 'days').subtract(1, 'months').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#clone before manipulating the moment. More info on cloning.

Add 1.0.0+

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

Mutates the original moment by adding time.

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

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

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

moment().add(7, 'd');
Key Shorthand
years y
quarters Q
months M
weeks w
days d
hours h
minutes m
seconds s
milliseconds ms

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

moment().add(7, 'days').add(1, 'months'); // 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(1000000, 'milliseconds'); // a million milliseconds
moment().add(360, 'days'); // 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.

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

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

Adding a month will add the specified number of months to the date.

moment([2010, 1, 28]);                 // February 28
moment([2010, 1, 28]).add(1, 'month'); // March 28
var m = moment(new Date(2011, 2, 12, 5, 0, 0)); // the day before DST in the US
m.hours(); // 5
m.add(1, 'days').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(24, 'hours').hours(); // 6 (but you may have to set the timezone first)

Alternatively, you can use durations to add to moments.

var duration = moment.duration({'days' : 1});
moment([2012, 0, 31]).add(duration); // February 1

Before version 2.8.0, the moment#add(String, Number) syntax was also supported. It has been deprecated in favor of moment#add(Number, String).

moment().add('seconds', 1); // Deprecated in 2.8.0
moment().add(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

moment().add(1.5, 'months') == moment().add(2, 'months')
moment().add(.7, 'years') == moment().add(8, 'months') //.7*12 = 8.4, rounded to 8

Subtract 1.0.0+

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

Mutates the original moment by subtracting time.

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

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

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

moment().subtract('seconds', 1); // Deprecated in 2.8.0
moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

Note that in order to make the operations moment.add(-.5, 'days') and moment.subtract(.5, 'days') equivalent, -.5, -1.5, -2.5, etc are rounded down.

Start of Time 1.7.0+

edit
moment().startOf(String);

Mutates the original moment by setting it to the start of a unit of time.

moment().startOf('year');    // set to January 1st, 12:00 am this year
moment().startOf('month');   // set to the first of this month, 12:00 am
moment().startOf('quarter');  // set to the beginning of the current quarter, 1st day of months, 12:00 am
moment().startOf('week');    // set to the first day of this week, 12:00 am
moment().startOf('isoWeek'); // set to the first day of this week according to ISO 8601, 12:00 am
moment().startOf('day');     // set to 12:00 am today
moment().startOf('date');     // set to 12:00 am today
moment().startOf('hour');    // set to now, but with 0 mins, 0 secs, and 0 ms
moment().startOf('minute');  // set to now, but with 0 seconds and 0 milliseconds
moment().startOf('second');  // same as moment().milliseconds(0);

These shortcuts are essentially the same as the following.

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)

As of version 2.0.0, moment#startOf('day') replaced moment#sod.

Note: moment#startOf('week') was added in version 2.0.0.

As of version 2.1.0, moment#startOf('week') uses the locale aware week start day.

Note: moment#startOf('isoWeek') was added in version 2.2.0.

Note: moment#startOf('date') was added as an alias for day in 2.13.0

End of Time 1.7.0+

edit
moment().endOf(String);

Mutates the original moment by setting it to the end of a unit of time.

This is the same as moment#startOf, only instead of setting to the start of a unit of time, it sets to the end of a unit of time.

moment().endOf("year"); // set the moment to 12-31 23:59:59.999 this year

As of version 2.0.0, moment#endOf('day') replaced moment#eod.

Note: moment#endOf('week') was added in version 2.0.0.

As of version 2.1.0, moment#endOf('week') uses the locale aware week start day.

Maximum From 2.1.0, Deprecated 2.7.0

edit
moment().max(Moment|String|Number|Date|Array);

Note: This function has been deprecated in 2.7.0. Consider moment.min instead.


Limits the moment to a maximum of another moment value. So a.max(b) is the same as a = moment.min(a, b) (note that max is converted to min).

Sometimes, server clocks are not quite in sync with client clocks. This ends up displaying humanized strings such as "in a few seconds" rather than "a few seconds ago". You can prevent that with moment#max():

This is the counterpart for moment#min.

var momentFromServer = moment(input);
var clampedMoment = momentFromServer.max();

You can pass anything to moment#max that you would pass to moment().

moment().max(moment().add(1, 'd'));
moment().max("2013-04-20T20:00:00+0800");
moment().max("Jan 1 2001", "MMM D YYYY");
moment().max(new Date(2012, 1, 8));

Minimum From 2.1.0, Deprecated 2.7.0

edit
moment().min(Moment|String|Number|Date|Array);

Note: This function has been deprecated in 2.7.0. Consider moment.max instead.


Limits the moment to a minimum of another moment value. So a.min(b) is the same as a = moment.max(a, b) (note that min is converted to max).

This is the counterpart for moment#max.

moment().min("2013-04-20T20:00:00+0800");

This can be used in conjunction with moment#max to clamp a moment to a range.

var start  = moment().startOf('week');
var end    = moment().endOf('week');
var actual = moment().min(start).max(end);

Local 1.5.0+

edit
moment().local();

Sets a flag on the original moment to use local time to display a moment instead of the original moment's time.

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

Local can also be used to convert out of a fixed offset mode:

moment.parseZone('2016-05-03T22:15:01+02:00').local().format(); // "2016-05-03T15:15:01-05:00"

See moment.utc() for more information on UTC mode.

UTC 1.5.0+

edit
moment().utc();

Sets a flag on the original moment to use UTC to display a moment instead of the original moment's time.

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

UTC can also be used to convert out of a fixed offset mode:

moment.parseZone('2016-05-03T22:15:01+02:00').utc().format(); //"2016-05-03T20:15:01Z"

See moment.utc() for more information on UTC mode.

UTC offset 2.9.0++

edit
moment().utcOffset();
moment().utcOffset(Number|String);
moment().utcOffset(Number|String, Boolean);

Get or set the UTC offset in minutes.

Note: Unlike moment.fn.zone this function returns the real offset from UTC, not the reverse offset (as returned by Date.prototype.getTimezoneOffset).

Getting the utcOffset of the current object:

moment().utcOffset(); // (-240, -120, -60, 0, 60, 120, 240, etc.)

Setting the UTC offset by supplying minutes. The offset is set on the moment object that utcOffset() is called on. If you are wanting to set the offset globally, try using moment-timezone . Note that once you set an offset, it's fixed and won't change on its own (i.e there are no DST rules). If you want an actual time zone -- time in a particular location, like America/Los_Angeles, consider moment-timezone .

moment().utcOffset(120);

If the input is less than 16 and greater than -16, it will interpret your input as hours instead.

// these are equivalent
moment().utcOffset(8);  // set hours offset
moment().utcOffset(480);  // set minutes offset (8 * 60)

It is also possible to set the UTC offset from a string.

// these are equivalent
moment().utcOffset("+08:00");
moment().utcOffset(8);
moment().utcOffset(480);

moment#utcOffset will search the string for the first match of +00:00 +0000 -00:00 -0000 Z, so you can even pass an ISO8601 formatted string and the moment will be changed to that UTC offset.

Note that the string, if not 'Z', is required to start with the + or - character.

moment().utcOffset("2013-03-07T07:00:00+08:00");

The utcOffset function has an optional second parameter which accepts a boolean value indicating whether to keep the existing time of day.

  • Passing false (the default) will keep the same instant in Universal Time, but the local time will change.

  • Passing true will keep the same local time, but at the expense of choosing a different point in Universal Time.

One use of this feature is if you want to construct a moment with a specific time zone offset using only numeric input values:

moment([2016, 0, 1, 0, 0, 0]).utcOffset(-5, true) // Equivalent to "2016-01-01T00:00:00-05:00"

Time zone Offset From 1.2.0, deprecated 2.9.0+

edit
moment().zone();
moment().zone(Number|String);

Note: This function has been deprecated in 2.9.0. Consider moment.fn.utcOffset instead.

Get the time zone offset in minutes.

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

As of version 2.1.0, it is possible to set the offset by passing in the number of minutes offset from GMT.

moment().zone(120);

If the input is less than 16 and greater than -16, it will interpret your input as hours instead.

// these are equivalent
moment().zone(480);
moment().zone(8);

It is also possible to set the zone from a string.

moment().zone("-08:00");

moment#zone will search the string for the first match of +00:00 +0000 -00:00 -0000, so you can even pass an ISO8601 formatted string and the moment will be changed to that zone.

moment().zone("2013-03-07T07:00:00-08:00");

Once parsing and manipulation are done, you need some way to display the moment.

Format 1.0.0+

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

This is the most robust display option. It takes a string of tokens and replaces them with their corresponding values.

moment().format();                                // "2014-09-08T08:02:17-05:00" (ISO 8601, no fractional seconds)
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().format("[Today is] dddd");               // "Today is Sunday"
moment('gibberish').format('YYYY MM DD');         // "Invalid date"
Token Output
Month M 1 2 ... 11 12
Mo 1st 2nd ... 11th 12th
MM 01 02 ... 11 12
MMM Jan Feb ... Nov Dec
MMMM January February ... November December
Quarter Q 1 2 3 4
Qo 1st 2nd 3rd 4th
Day of Month D 1 2 ... 30 31
Do 1st 2nd ... 30th 31st
DD 01 02 ... 30 31
Day of Year DDD 1 2 ... 364 365
DDDo 1st 2nd ... 364th 365th
DDDD 001 002 ... 364 365
Day of Week d 0 1 ... 5 6
do 0th 1st ... 5th 6th
dd Su Mo ... Fr Sa
ddd Sun Mon ... Fri Sat
dddd Sunday Monday ... Friday Saturday
Day of Week (Locale) e 0 1 ... 5 6
Day of Week (ISO) E 1 2 ... 6 7
Week of Year w 1 2 ... 52 53
wo 1st 2nd ... 52nd 53rd
ww 01 02 ... 52 53
Week of Year (ISO) W 1 2 ... 52 53
Wo 1st 2nd ... 52nd 53rd
WW 01 02 ... 52 53
Year YY 70 71 ... 29 30
YYYY 1970 1971 ... 2029 2030
YYYYYY -001970 -001971 ... +001907 +001971
Note: Expanded Years (Covering the full time value range of approximately 273,790 years forward or backward from 01 January, 1970)
Y 1970 1971 ... 9999 +10000 +10001
Note: This complies with the ISO 8601 standard for dates past the year 9999
Era Year y 1 2 ... 2020 ...
Era N BC AD
Note: Abbr era name
NN BC AD
Note: Narrow era name
NNN Before Christ, Anno Domini
Note: Full era name
Week Year gg 70 71 ... 29 30
gggg 1970 1971 ... 2029 2030
Week Year (ISO) GG 70 71 ... 29 30
GGGG 1970 1971 ... 2029 2030
AM/PM A AM PM
a am pm
Hour H 0 1 ... 22 23
HH 00 01 ... 22 23
h 1 2 ... 11 12
hh 01 02 ... 11 12
k 1 2 ... 23 24
kk 01 02 ... 23 24
Minute m 0 1 ... 58 59
mm 00 01 ... 58 59
Second s 0 1 ... 58 59
ss 00 01 ... 58 59
Fractional Second S 0 1 ... 8 9
SS 00 01 ... 98 99
SSS 000 001 ... 998 999
SSSS ... SSSSSSSSS 000[0..] 001[0..] ... 998[0..] 999[0..]
Time Zone z or zz EST CST ... MST PST
Note: as of 1.6.0, the z/zz format tokens have been deprecated from plain moment objects. Read more about it here. However, they *do* work if you are using a specific time zone with the moment-timezone addon.
Z -07:00 -06:00 ... +06:00 +07:00
ZZ -0700 -0600 ... +0600 +0700
Unix Timestamp X 1360013296
Unix Millisecond Timestamp x 1360013296123

X was added in 2.0.0.

e E gg gggg GG GGGG were added in 2.1.0.

x was added in 2.8.4.

SSSS to SSSSSSSSS were added in 2.10.5. They display 3 significant digits and the rest is filled with zeros.

k and kk were added in 2.13.0.

Localized formats

Because preferred formatting differs based on locale, there are a few tokens that can be used to format a moment based on its locale.

There are upper and lower case variations on the same formats. The lowercase version is intended to be the shortened version of its uppercase counterpart.

Time LT 8:30 PM
Time with seconds LTS 8:30:25 PM
Month numeral, day of month, year L 09/04/1986
l 9/4/1986
Month name, day of month, year LL September 4, 1986
ll Sep 4, 1986
Month name, day of month, year, time LLL September 4, 1986 8:30 PM
lll Sep 4, 1986 8:30 PM
Month name, day of month, day of week, year, time LLLL Thursday, September 4, 1986 8:30 PM
llll Thu, Sep 4, 1986 8:30 PM

l ll lll llll are available in 2.0.0. LTS was added in 2.8.4.

Escaping characters

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

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

Similarities and differences with LDML

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 across different locales, see this chart of date formatting tokens.

Formatting speed

To compare Moment.js formatting speed against other libraries, check out this comparison against other libraries .

Other tokens

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

Default format

Calling moment#format without a format will default to moment.defaultFormat. Out of the box, moment.defaultFormat is the ISO8601 format YYYY-MM-DDTHH:mm:ssZ.

As of version 2.13.0, when in UTC mode, the default format is governed by moment.defaultFormatUtc which is in the format YYYY-MM-DDTHH:mm:ss[Z]. This returns Z as the offset, instead of +00:00.

In certain instances, a local timezone (such as Atlantic/Reykjavik) may have a zero offset, and will be considered to be UTC. In such cases, it may be useful to set moment.defaultFormat and moment.defaultFormatUtc to use the same formatting.

Changing the value of moment.defaultFormat will only affect formatting, and will not affect parsing. for example:

moment.defaultFormat = "DD.MM.YYYY HH:mm";
// parse with .toDate()
moment('20.07.2018 09:19').toDate() // Invalid date
// format the date string with the new defaultFormat then parse
moment('20.07.2018 09:19', moment.defaultFormat).toDate() // Fri Jul 20 2018 09:19:00 GMT+0300

Time from now 1.0.0+

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

A common way of displaying time is handled by moment#fromNow. This is sometimes called timeago or relative time.

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

If you pass true, you can get the value without the suffix.

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

The base strings are customized by the current locale. Time is rounded to the nearest second.

The breakdown of which string is displayed for each length of time is outlined in the table below.

Range Key Sample Output
0 to 44 seconds s a few seconds ago
unset ss 44 seconds ago
45 to 89 seconds m a minute ago
90 seconds to 44 minutes mm 2 minutes ago ... 44 minutes ago
45 to 89 minutes h an hour ago
90 minutes to 21 hours hh 2 hours ago ... 21 hours ago
22 to 35 hours d a day ago
36 hours to 25 days dd 2 days ago ... 25 days ago
26 to 45 days M a month ago
45 to 319 days MM 2 months ago ... 10 months ago
320 to 547 days (1.5 years) y a year ago
548 days+ yy 2 years ago ... 20 years ago

Note: From version 2.10.3, if the target moment object is invalid the result is the localized Invalid date string.

Note: The ss key was added in 2.18.0. It is an optional threshold. It will never display UNLESS the user manually sets the ss threshold. Until the ss threshold is set, it defaults to the value of the s threshold minus 1 (so, invisible to the user).

Time from X 1.0.0+

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

You may want to display a moment in relation to a time other than now. In that case, you can use moment#from.

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

The first parameter is anything you can pass to moment() or an actual Moment.

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

Like moment#fromNow, passing true as the second parameter returns 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]);
end.from(start);       // "in 5 days"
end.from(start, true); // "5 days"

From version 2.10.3, if any of the endpoints are invalid the result is the localized Invalid date string.

Time to now 2.10.3+

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

A common way of displaying time is handled by moment#toNow. This is sometimes called timeago or relative time.

This is similar to moment.fromNow, but gives the opposite interval: a.fromNow() = - a.toNow().

This is similar to moment.to, but is special-cased for the current time. Use moment.to, if you want to control the two end points of the interval.

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

If you pass true, you can get the value without the prefix.

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

The base strings are customized by the current locale.

The breakdown of which string is displayed for each length of time is outlined in the table below.

Range Key Sample Output
0 to 44 seconds s in seconds
45 to 89 seconds m in a minute
90 seconds to 44 minutes mm in 2 minutes ... in 44 minutes
45 to 89 minutes h in an hour
90 minutes to 21 hours hh in 2 hours ... in 21 hours
22 to 35 hours d in a day
36 hours to 25 days dd in 2 days ... in 25 days
26 to 45 days M in a month
45 to 319 days MM in 2 months ... in 10 months
320 to 547 days (1.5 years) y in a year
548 days+ yy in 2 years ... in 20 years

From version 2.10.3, if the target moment object is invalid the result is the localized Invalid date string.

Time to X 2.10.3+

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

You may want to display a moment in relation to a time other than now. In that case, you can use moment#to.

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

The first parameter is anything you can pass to moment() or an actual Moment.

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

Like moment#toNow, passing true as the second parameter returns 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]);
end.to(start);       // "5 days ago"
end.to(start, true); // "5 days"

From version 2.10.3, if any of the endpoints are invalid the result is the localized Invalid date string.

Calendar Time 1.3.0+

edit
moment().calendar();
moment().calendar(referenceDay);
moment().calendar(referenceDay, formats);  // from 2.10.5
moment().calendar(formats);  // from 2.25.0

Calendar time displays time relative to a given referenceDay (defaults to the start of today), but does so slightly differently than moment#fromNow.

moment#calendar will format a date with different strings depending on how close to referenceDay's date (today by default) the date is.

Last week Last Monday at 2:30 AM
The day before Yesterday at 2:30 AM
The same day Today at 2:30 AM
The next day Tomorrow at 2:30 AM
The next week Sunday at 2:30 AM
Everything else 7/10/2011

These strings are localized, and can be customized.

From 2.10.5 moment supports specifying calendar output formats per invocation:

moment().calendar(null, {
    sameDay: '[Today]',
    nextDay: '[Tomorrow]',
    nextWeek: 'dddd',
    lastDay: '[Yesterday]',
    lastWeek: '[Last] dddd',
    sameElse: 'DD/MM/YYYY'
});

sameElse is used as the format when the moment is more than a week away from the referenceDay

Note: From version 2.14.0 the formats argument to calendar can be a callback that is executed within the moment context with a single argument now:

moment().calendar(null, {
  sameDay: function (now) {
    if (this.isBefore(now)) {
      return '[Will Happen Today]';
    } else {
      return '[Happened Today]';
    }
    /* ... */
  }
});

Note: From version 2.25.0 you can only pass a formats argument, it could be an object of strings and functions:

moment().calendar({
    sameDay: '[Today]',
    nextDay: '[Tomorrow]',
    nextWeek: 'dddd',
    lastDay: '[Yesterday]',
    lastWeek: '[Last] dddd',
    sameElse: 'DD/MM/YYYY'
});

moment().calendar({
  sameDay: function (now) {
    if (this.isBefore(now)) {
      return '[Will Happen Today]';
    } else {
      return '[Happened Today]';
    }
    /* ... */
  }
});

Difference 1.0.0+

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

To get the difference in milliseconds, use moment#diff like you would use moment#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

To get the duration of a difference between two moments, you can pass diff as an argument into moment#duration. See the docs on moment#duration for more info.

The supported measurements are years, months, weeks, days, hours, minutes, and seconds. For ease of development, the singular forms are supported as of 2.0.0. Units of measurement other than milliseconds are available in version 1.1.1.

By default, moment#diff will truncate the result to zero decimal places, returning an integer. If you want a floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned a number rounded to the nearest integer, not a truncated number.

var a = moment([2008, 9]);
var b = moment([2007, 0]);
a.diff(b, 'years');       // 1
a.diff(b, 'years', true); // 1.75

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

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

An 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

Month and year diffs

moment#diff has some special handling for month and year diffs. It is optimized to ensure that two months with the same date are always a whole number apart.

So Jan 15 to Feb 15 should be exactly 1 month.

Feb 28 to Mar 28 should be exactly 1 month.

Feb 28 2011 to Feb 28 2012 should be exactly 1 year.

See more discussion on the month and year diffs here

This change to month and year diffs was made in 2.0.0. As of version 2.9.0 diff also support quarter unit.

Unix Timestamp (milliseconds) 1.0.0+

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

moment#valueOf simply outputs the number of milliseconds since the Unix Epoch, just like Date#valueOf.

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

To get a Unix timestamp (the number of seconds since the epoch) from a Moment, use moment#unix.

Note: ECMAScript calls this a "Time Value"

Unix Timestamp (seconds) 1.6.0+

edit
moment().unix();

moment#unix outputs a Unix timestamp (the number of seconds since the Unix Epoch).

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

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

Days in Month 1.5.0+

edit
moment().daysInMonth();

Get the number of days in the current month.

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

As Javascript Date 1.0.0+

edit
moment().toDate();

To get a copy of the native Date object that Moment.js wraps, use moment#toDate.

This will return a copy of the Date that the moment uses, so any changes to that Date will not cause moment to change. If you want to change the moment Date, see moment#manipulate or moment#set.

moment#native has been replaced by moment#toDate and has been deprecated as of 1.6.0.

As Array 1.7.0+

edit
moment().toArray();

This returns an array that mirrors the parameters from new Date().

moment().toArray(); // [2013, 1, 4, 14, 40, 16, 154];

As JSON 2.0.0+

edit
moment().toJSON();

When serializing an object to JSON, if there is a Moment object, it will be represented as an ISO8601 string, adjusted to UTC.

JSON.stringify({
    postDate : moment()
}); // '{"postDate":"2013-02-04T22:44:30.652Z"}'

If instead you would like an ISO8601 string that reflects the moment's utcOffset(), then you can modify the toJSON function like this:

moment.fn.toJSON = function() { return this.format(); }

This changes the behavior as follows:

JSON.stringify({
    postDate : moment()
}); // '{"postDate":"2013-02-04T14:44:30-08:00"}'

As ISO 8601 String 2.1.0+

edit
moment().toISOString();
moment().toISOString(keepOffset); // from 2.20.0

Formats a string to the ISO8601 standard.

moment().toISOString() // 2013-02-04T22:44:30.652Z

Note that .toISOString() returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString(), as outlined in the ES2015 specification . From version 2.20.0, you may call .toISOString(true) to prevent UTC conversion.

From version 2.8.4 the native Date.prototype.toISOString is used if available, for performance reasons.

As Object 2.10.5+

edit
moment().toObject();

This returns an object containing year, month, day-of-month, hour, minute, seconds, milliseconds.

moment().toObject()  // {
                     //     years: 2015
                     //     months: 6
                     //     date: 26,
                     //     hours: 1,
                     //     minutes: 53,
                     //     seconds: 14,
                     //     milliseconds: 600
                     // }

As String 2.1.0+

edit
moment().toString();

Returns an english string in a similar format to JS Date's .toString().

moment().toString() // "Sat Apr 30 2016 16:59:46 GMT-0500"

Inspect 2.16.0+

edit
moment().inspect();

Returns a machine readable string, that can be evaluated to produce the same moment. Because of the name its also used in node interactive shell to display objects.

moment().inspect() // 'moment("2016-11-09T22:23:27.861")'
moment.utc().inspect() // 'moment.utc("2016-11-10T06:24:10.638+00:00")'
moment.parseZone('2016-11-10T06:24:12.958+05:00').inspect() // 'moment.parseZone("2016-11-10T06:24:12.958+05:00")'
moment(new Date('nope')).inspect() // 'moment.invalid(/* Invalid Date */)'
moment('blah', 'YYYY').inspect() // 'moment.invalid(/* blah */)'

Note: This function is mostly intended for debugging, not all cases are handled precisely.

Is Before 2.0.0+

edit
moment().isBefore(Moment|String|Number|Date|Array);
moment().isBefore(Moment|String|Number|Date|Array, String);

Check if a moment is before another moment. The first argument will be parsed as a moment, if not already so.

moment('2010-10-20').isBefore('2010-10-21'); // true

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.

moment('2010-10-20').isBefore('2010-12-31', 'year'); // false
moment('2010-10-20').isBefore('2011-01-01', 'year'); // true

Like moment#isAfter and moment#isSame, any of the units of time that are supported for moment#startOf are supported for moment#isBefore.

year month week isoWeek day hour minute second

If nothing is passed to moment#isBefore, it will default to the current time.

NOTE: moment().isBefore() has undefined behavior and should not be used! If the code runs fast the initial created moment would be the same as the one created in isBefore to perform the check, so the result would be false. But if the code runs slower it's possible that the moment created in isBefore is measurably after the one created in moment(), so the call would return true.

Is Same 2.0.0+

edit
moment().isSame(Moment|String|Number|Date|Array);
moment().isSame(Moment|String|Number|Date|Array, String);

Check if a moment is the same as another moment. The first argument will be parsed as a moment, if not already so.

moment('2010-10-20').isSame('2010-10-20'); // true

If you want to limit the granularity to a unit other than milliseconds, pass it as the second parameter.

moment('2010-10-20').isSame('2009-12-31', 'year');  // false
moment('2010-10-20').isSame('2010-01-01', 'year');  // true
moment('2010-10-20').isSame('2010-12-31', 'year');  // true
moment('2010-10-20').isSame('2011-01-01', 'year');  // false

When including a second parameter, it will match all units equal or larger. Passing in month will check month and year. Passing in day will check day, month, and year.

moment('2010-01-01').isSame('2011-01-01', 'month'); // false, different year
moment('2010-01-01').isSame('2010-02-01', 'day');   // false, different month

Like moment#isAfter and moment#isBefore, any of the units of time that are supported for moment#startOf are supported for moment#isSame.

year month week isoWeek day hour minute second

If the two moments have different timezones, the timezone of the first moment will be used for the comparison.

// Note: Australia/Sydney is UTC+11:00 on these dates
moment.tz("2018-11-09T10:00:00", "Australia/Sydney").isSame(moment.tz("2018-11-08T12:00:00", "UTC"), "day"); // false
moment.tz("2018-11-08T12:00:00", "UTC").isSame(moment.tz("2018-11-09T10:00:00", "Australia/Sydney"), "day"); // true

NOTE: moment().isSame() has undefined behavior and should not be used! If the code runs fast the initial created moment would be the same as the one created in isSame to perform the check, so the result would be true. But if the code runs slower it's possible that the moment created in isSame is measurably after the one created in moment(), so the call would return false.

Is After 2.0.0+

edit
moment().isAfter(Moment|String|Number|Date|Array);
moment().isAfter(Moment|String|Number|Date|Array, String);

Check if a moment is after another moment. The first argument will be parsed as a moment, if not already so.

moment('2010-10-20').isAfter('2010-10-19'); // true

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.

moment('2010-10-20').isAfter('2010-01-01', 'year'); // false
moment('2010-10-20').isAfter('2009-12-31', 'year'); // true

Like moment#isSame and moment#isBefore, any of the units of time that are supported for moment#startOf are supported for moment#isAfter.

year month week isoWeek day hour minute second

If nothing is passed to moment#isAfter, it will default to the current time.

moment().isAfter(); // false

Is Same or Before 2.11.0+

edit
moment().isSameOrBefore(Moment|String|Number|Date|Array);
moment().isSameOrBefore(Moment|String|Number|Date|Array, String);

Check if a moment is before or the same as another moment. The first argument will be parsed as a moment, if not already so.

moment('2010-10-20').isSameOrBefore('2010-10-21');  // true
moment('2010-10-20').isSameOrBefore('2010-10-20');  // true
moment('2010-10-20').isSameOrBefore('2010-10-19');  // false

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.

moment('2010-10-20').isSameOrBefore('2009-12-31', 'year'); // false
moment('2010-10-20').isSameOrBefore('2010-12-31', 'year'); // true
moment('2010-10-20').isSameOrBefore('2011-01-01', 'year'); // true

Like moment#isAfter and moment#isSame, any of the units of time that are supported for moment#startOf are supported for moment#isSameOrBefore:

year month week isoWeek day hour minute second

Is Same or After 2.11.0+

edit
moment().isSameOrAfter(Moment|String|Number|Date|Array);
moment().isSameOrAfter(Moment|String|Number|Date|Array, String);

Check if a moment is after or the same as another moment. The first argument will be parsed as a moment, if not already so.

moment('2010-10-20').isSameOrAfter('2010-10-19'); // true
moment('2010-10-20').isSameOrAfter('2010-10-20'); // true
moment('2010-10-20').isSameOrAfter('2010-10-21'); // false

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.

moment('2010-10-20').isSameOrAfter('2011-12-31', 'year'); // false
moment('2010-10-20').isSameOrAfter('2010-01-01', 'year'); // true
moment('2010-10-20').isSameOrAfter('2009-12-31', 'year'); // true

Like moment#isSame and moment#isBefore, any of the units of time that are supported for moment#startOf are supported for moment#isSameOrAfter:

year month week isoWeek day hour minute second

Is Between 2.9.0+

edit
//From 2.13.0 onward
moment().isBetween(moment-like, moment-like);
moment().isBetween(moment-like, moment-like, String);
moment().isBetween(moment-like, moment-like, String, String);
// where moment-like is Moment|String|Number|Date|Array

//2.9.0 to 2.12.0
moment().isBetween(moment-like, moment-like);
moment().isBetween(moment-like, moment-like, String);
// where moment-like is Moment|String|Number|Date|Array

Check if a moment is between two other moments, optionally looking at unit scale (minutes, hours, days, etc). The match is exclusive. The first two arguments will be parsed as moments, if not already so.

moment('2010-10-20').isBetween('2010-10-19', '2010-10-25'); // true
moment('2010-10-20').isBetween('2010-10-19', undefined); // true, since moment(undefined) evaluates as moment()

Note that the order of the two arguments matter: the "smaller" date should be in the first argument.

moment('2010-10-20').isBetween('2010-10-19', '2010-10-25'); // true
moment('2010-10-20').isBetween('2010-10-25', '2010-10-19'); // false

If you want to limit the granularity to a unit other than milliseconds, pass the units as the third parameter.

moment('2010-10-20').isBetween('2010-01-01', '2012-01-01', 'year'); // false
moment('2010-10-20').isBetween('2009-12-31', '2012-01-01', 'year'); // true

Like moment#isSame, moment#isBefore, moment#isAfter any of the units of time that are supported for moment#startOf are supported for moment#isBetween. Year, month, week, isoWeek, day, hour, minute, and second.

Version 2.13.0 introduces inclusivity. A [ indicates inclusion of a value. A ( indicates exclusion. If the inclusivity parameter is used, both indicators must be passed.

moment('2016-10-30').isBetween('2016-10-30', '2016-12-30', undefined, '()'); //false
moment('2016-10-30').isBetween('2016-10-30', '2016-12-30', undefined, '[)'); //true
moment('2016-10-30').isBetween('2016-01-01', '2016-10-30', undefined, '()'); //false
moment('2016-10-30').isBetween('2016-01-01', '2016-10-30', undefined, '(]'); //true
moment('2016-10-30').isBetween('2016-10-30', '2016-10-30', undefined, '[]'); //true

Note that in the event that the from and to parameters are the same, but the inclusivity parameters are different, false will preside.

moment('2016-10-30').isBetween('2016-10-30', '2016-10-30', undefined, '(]'); //false

If the inclusivity parameter is not specified, Moment will default to ().

Is Daylight Saving Time 1.2.0+

edit
moment().isDST();

moment#isDST checks if the current moment is in daylight saving time.

moment([2011, 2, 12]).isDST(); // false, March 12 2011 is not DST
moment([2011, 2, 14]).isDST(); // true, March 14 2011 is DST
// This example is for "en" locale: https://www.timeanddate.com/time/dst/2011.html

Is DST Shifted From 2.3.0, Deprecated 2.14.0

edit
moment('2013-03-10 2:30', 'YYYY-MM-DD HH:mm').isDSTShifted()

Note: As of version 2.14.0 this function is deprecated. It doesn't give the right answer after modifying the moment object. For more information refer to moment/3160

Another important piece of validation is to know if the date has been moved by a DST. For example, in most of the United States:

moment('2013-03-10 2:30', 'YYYY-MM-DD HH:mm').format(); //=> '2013-03-10T01:30:00-05:00'

This is because daylight saving time shifts the time from 2:00 to 3:00, so 2:30 isn't a real time. The resulting time is browser-dependent, either adjusting the time forward or backwards. Use moment#isDSTShifted to test for this condition.

Note: before 2.3.0, Moment objects in this condition always returned false for moment#isValid; they now return true.

Is Leap Year 1.0.0+

edit
moment().isLeapYear();

moment#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

Is a Moment 1.5.0+

edit
moment.isMoment(obj);

To check if a variable is a moment object, use moment.isMoment().

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

From version 2.11.0, you can also test for a moment object by instanceof operator:

moment() instanceof moment // true

Is a Date 2.9.0+

edit
moment.isDate(obj);

To check if a variable is a native js Date object, use moment.isDate().

moment.isDate(); // false
moment.isDate(new Date()); // true
moment.isDate(moment()); // false

Moment.js has robust support for internationalization.

You can load multiple locales and easily switch between them.

In addition to assigning a global locale, you can assign a locale to a specific moment.

Changing locale globally 1.0.0+

edit
// From 2.8.1 onward
moment.locale(String);
moment.locale(String[]);
moment.locale(String, Object);

// Deprecated in 2.8.1
moment.lang(String);
moment.lang(String[]);
moment.lang(String, Object);

By default, Moment.js comes with English (United States) locale strings. If you need other locales, you can load them into Moment.js for later use.

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

More details on each of the parts of the locale bundle can be found in the customization section.

moment.locale('fr', {
    months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
    monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
    monthsParseExact : true,
    weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
    weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
    weekdaysMin : 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Aujourd’hui à] LT',
        nextDay : '[Demain à] LT',
        nextWeek : 'dddd [à] LT',
        lastDay : '[Hier à] LT',
        lastWeek : 'dddd [dernier à] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'dans %s',
        past : 'il y a %s',
        s : 'quelques 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 : 'un an',
        yy : '%d ans'
    },
    dayOfMonthOrdinalParse : /\d{1,2}(er|e)/,
    ordinal : function (number) {
        return number + (number === 1 ? 'er' : 'e');
    },
    meridiemParse : /PD|MD/,
    isPM : function (input) {
        return input.charAt(0) === 'M';
    },
    // In case the meridiem units are not separated around 12, then implement
    // this function (look at locale/id.js for an example).
    // meridiemHour : function (hour, meridiem) {
    //     return /* 0-23 hour, given meridiem token and hour 1-12 */ ;
    // },
    meridiem : function (hours, minutes, isLower) {
        return hours < 12 ? 'PD' : 'MD';
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // Used to determine first week of the year.
    }
});

Details about week.dow and week.doy can be found in the customization section.

Once you load a locale, it becomes the active locale. To change active locales, simply call moment.locale with the key of a loaded locale.

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

As of 2.21.0, Moment will console.warn if the locale is unavailable.

As of 2.8.0, changing the global locale doesn't affect existing instances.

moment.locale('fr');
var m = moment(1316116057189);
m.fromNow(); // il y a une heure

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

moment.locale returns the locale used. This is useful because Moment won't change locales if it doesn't know the one you specify.

moment.locale('fr'); // 'fr'
moment.locale('tq'); // 'fr'

You may also specify a list of locales, and Moment will use the first one it has localizations for.

moment.locale(['tq', 'fr']); // 'fr'

Moment will also try locale specifier substrings from most-specific to least-specific until it finds a locale it knows. This is useful when supplying Moment with a locale string pulled from the user's environment, such as window.navigator.language.

moment.locale('en-nz'); // 'en'

Finally, Moment will search intelligently through an array of locales and their substrings.

moment.locale(['en-nz', 'en-au']); // 'en-au', not 'en'

The logic works as follows -- the next locale is picked and tried as-is. If that fails, the code normally tries to chop the last bit (normally the country designation) and try again. However, if the next array element has the same or longer prefix as the one to be tried, the iteration continues. So for example if the array has the sequence

"AA-BB", "AA-CC", "XX-YY"

then first "AA-BB" is tried, then a naive solution would try "AA", but this one instead checks to see that "AA-CC" is actually more concrete than "AA", so it tries "AA-CC" next, and only after it fails (if it fails) it tries "AA", because "XX-YY" does not have "AA" as prefix. So in the end the following locales are tried in this order (assuming all fail so the next one is tried):

"AA-BB", "AA-CC", "AA", "XX-YY", "XX"

Changing locales locally 1.7.0+

edit
// From version 2.8.1 onward
moment().locale(String|String[]|Boolean);

// Deprecated version 2.8.1
moment().lang(String|String[]|Boolean);

A global locale configuration can be problematic when passing around moments that may need to be formatted into different locale.

moment.locale('en'); // default the locale to English
var localLocale = moment();

localLocale.locale('fr'); // set this instance to use French
localLocale.format('LLLL'); // dimanche 15 juillet 2012 11:01
moment().format('LLLL'); // Sunday, July 15 2012 11:01 AM

moment.locale('es'); // change the global locale to Spanish
localLocale.format('LLLL'); // dimanche 15 juillet 2012 11:01
moment().format('LLLL'); // Domingo 15 Julio 2012 11:01

localLocale.locale(['tq', 'fr']); // set this instance to the first localization found
localLocale.format('LLLL'); // dimanche 15 juillet 2012 11:01
moment().format('LLLL'); // Sunday, July 15 2012 11:01 AM

localLocale.locale(false); // reset the instance locale
localLocale.format('LLLL'); // Domingo 15 Julio 2012 11:01
moment().format('LLLL'); // Domingo 15 Julio 2012 11:01

If you call moment#locale with no parameters, you get back the locale configuration that would be used for that moment.

var fr = moment().locale('fr');
fr.localeData().months(moment([2012, 0])) // "janvier"
fr.locale('en');
fr.localeData().months(moment([2012, 0])) // "January"

If you need to access the locale data for a moment, this is the preferred way to do so.

As of 2.3.0, you can also specify an array of locale identifiers. It works the same way it does in the global locale configuration.

Loading locales in NodeJS 1.0.0+

edit
moment.locale(String);

Loading locales in NodeJS is super easy. If there is a locale file in moment/locale/ named after that key, import it first, then call moment.locale to load it.

var moment = require('moment');
//or
// import moment from 'moment';

// import locale file(s)
import 'moment/locale/fr';

moment.locale('fr');
moment(1316116057189).fromNow(); // il y a 6 ans

To save the step of loading individual locales (i.e. just load them all), import the moment/min/moment-with-locales module instead.

import moment from 'moment/min/moment-with-locales';

moment.locale('de');
moment(1316116057189).fromNow(); // vor 6 Jahren

If you want your locale supported, create a pull request to the develop branch with the required locale and unit test files.

Loading locales in the browser 1.0.0+

edit
// From 2.8.1 onward
moment.locale(String, Object);

// Deprecated in 2.8.1
moment.lang(String, Object);

Loading locales in the browser just requires you to include the locale files. Be sure to specify the charset to prevent encoding issues.

<script src="moment.js"></script>
<script src="locale/fr.js" charset="UTF-8"></script>
<script src="locale/pt.js" charset="UTF-8"></script>
<script>
  moment.locale('fr');  // Set the default/global locale
  // ...
</script>

There are minified versions of all locales together:

<script src="moment.js"></script>
<script src="min/locales.js" charset="UTF-8"></script>

To minimize HTTP requests, use our Grunt task to compile Moment with a custom list of locales:

grunt transpile:fr,it
<script src="min/moment-with-locales.custom.js" charset="UTF-8"></script>

If you are using JSPM as plugin manager, you should add the locale in your lib.

import * as moment from 'moment';
import 'moment/locale/fr';

Note: Locale files are defined in UMD style, so they should work seamlessly in all environments.

Adding your locale to Moment.js

edit

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

To run the tests in Node.js, do npm install, then grunt.

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

Checking the current Moment.js locale 1.6.0+

edit
// From version 2.8.1 onward
moment.locale();

// Deprecated in version 2.8.1
moment.lang();

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

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

As of version 2.12.0 it is possible to list all locales that have been loaded and are available to use: