Once parsing and manipulation are done, you need some way to display the moment.
Format 1.0.0+
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, NN, NNN | BC AD Note: Abbr era name |
ㅤ | NNNN | Before Christ, Anno Domini Note: Full era name |
ㅤ | NNNNN | BC AD Note: Narrow 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+
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+
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+
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+
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+
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+
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.
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+
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
.Unix Timestamp (seconds) 1.6.0+
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+
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+
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+
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+
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+
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+
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+
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+
moment().inspect();
Returns a machine readable string, that can be evaluated to produce the same moment. Because of the name it's 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.
Query
Is Before 2.0.0+
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+
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+
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+
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+
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+
//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+
moment().isDST();
moment#isDST
checks if the current moment is in daylight saving time.NOTE: This function is a HACK. moment has no way of knowing if a given time is in actual DST or not. Some time changes in a zone are DST related, some are not, and without complete timezone information it can't know.
Moment currently checks the winter and summer time, and if the offset matches the summer offset (and summer off is different than winter off), then it reports DST. This works in vast majority of cases, but as mentioned above, is not "correct" and won't work for all cases. So don't come to us complaining.
Event moment-timezone (at moment of writing 0.5.37) doesn't support DST info (i.e is the clock officially in DST at a given moment or not), so for things to get better some new stuff (and tzdata bundling) has to happen in moment-timezone.
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
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+
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+
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+
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
i18n
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+
// 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. } });
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+
// 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+
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+
// 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
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+
// 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:
moment.locales()
Listing the months and weekdays of the current Moment.js locale 2.3.0+
moment.months() moment.monthsShort() moment.weekdays() moment.weekdaysShort() moment.weekdaysMin()
It is sometimes useful to get the list of months or weekdays in a locale, for example when populating a dropdown menu.
moment.months();
Returns the list of months in the current locale.
[ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]
Similarly,
moment.monthsShort
returns abbreviated month names, and moment.weekdays
, moment.weekdaysShort
, moment.weekdaysMin
return lists of weekdays.You can pass an integer into each of those functions to get a specific month or weekday.
moment.weekdays(3); // 'Wednesday'
As of 2.13.0 you can pass a bool as the first parameter of the weekday functions. If true, the weekdays will be returned in locale specific order. For instance, in the Arabic locale, Saturday is the first day of the week, thus:
moment.locale('ar'); moment.weekdays(true); // lists weekdays Saturday-Friday in Arabic moment.weekdays(true, 2); //will result in Monday in Arabic
Note: Absent the locale specific parameter, weekdays always have Sunday as index 0, regardless of the local first day of the week.
Some locales make special considerations into account when formatting month names. For example, Dutch formats month abbreviations without a trailing period, but only if it's formatting the month between dashes. The
months
method supports passing a format in so that the months will be listed in the proper context.moment.locale('nl'); moment.monthsShort(); // ['jan.', 'feb.', 'mrt.', ...] moment.monthsShort('-MMM-'); // [ 'jan', 'feb', 'mrt', ...]
And finally, you can combine both the format option and the integer option.
moment.monthsShort('-MMM-', 3); // 'apr'
Accessing locale specific functionality 2.8.0+
localeData = moment.localeData() localeData.months(Moment) localeData.months() localeData.monthsShort(Moment) localeData.monthsShort() localeData.monthsParse(String) localeData.weekdays(Moment) localeData.weekdays() localeData.weekdays(Boolean) ## Added 2.24.0, sorts weekdays by locale localeData.weekdaysShort(Moment) localeData.weekdaysShort() localeData.weekdaysShort(Boolean) ## Added 2.24.0, sorts weekdays by locale localeData.weekdaysMin(Moment) localeData.weekdaysMin() localeData.weekdaysMin(Boolean) ## Added 2.24.0, sorts weekdays by locale localeData.weekdaysParse(String) localeData.longDateFormat(String) localeData.isPM(String) localeData.meridiem(Number, Number, Boolean) localeData.calendar(String, Moment) localeData.relativeTime(Number, Boolean, String, Boolean) localeData.pastFuture(Number, String) localeData.ordinal(Number) localeData.preparse(String) localeData.postformat(String) localeData.week(Moment) localeData.invalidDate() localeData.firstDayOfWeek() localeData.firstDayOfYear()
You can access the properties of the currently loaded locale through the
moment.localeData(key)
function. It returns the current locale or a locale with the given key:// get current locale var currentLocaleData = moment.localeData(); var frLocaleData = moment.localeData('fr');
The returned object has the following methods:
localeData.months(aMoment); // full month name of aMoment localeData.monthsShort(aMoment); // short month name of aMoment localeData.monthsParse(longOrShortMonthString); // returns month id (0 to 11) of input localeData.weekdays(aMoment); // full weekday name of aMoment localeData.weekdaysShort(aMoment); // short weekday name of aMoment localeData.weekdaysMin(aMoment); // min weekday name of aMoment localeData.weekdaysParse(minShortOrLongWeekdayString); // returns weekday id (0 to 6) of input localeData.longDateFormat(dateFormat); // returns the full format of abbreviated date-time formats LT, L, LL and so on localeData.isPM(amPmString); // returns true iff amPmString represents PM localeData.meridiem(hours, minutes, isLower); // returns am/pm string for particular time-of-day in upper/lower case localeData.calendar(key, aMoment); // returns a format that would be used for calendar representation. Key is one of 'sameDay', 'nextDay', 'lastDay', 'nextWeek', 'prevWeek', 'sameElse' localeData.relativeTime(number, withoutSuffix, key, isFuture); // returns relative time string, key is on of 's', 'm', 'mm', 'h', 'hh', 'd', 'dd', 'M', 'MM', 'y', 'yy'. Single letter when number is 1. localeData.pastFuture(diff, relTime); // convert relTime string to past or future string depending on diff localeData.ordinal(number); // convert number to ordinal string 1 -> 1st localeData.preparse(str); // called before parsing on every input string localeData.postformat(str); // called after formatting on every string localeData.week(aMoment); // returns week-of-year of aMoment localeData.invalidDate(); // returns a translation of 'Invalid date' localeData.firstDayOfWeek(); // 0-6 (Sunday to Saturday) localeData.firstDayOfYear(); // 0-15 Used to determine first week of the year.
Details about
firstDayOfYear
can be found in the customization section.Pseudo Locale 2.13.0+
moment.locale('x-pseudo')
As of version 2.13.0 moment optionally includes a pseudo locale. This locale will populate the dates with very obviously changed data. Pseudo locales can be useful when testing, as they make obvious what data has and has not been localized. Just include the pseudo-locale, and set moment's locale to x-pseudo. Text from Moment will be very easy to spot.
moment.locale('x-pseudo'); moment().format('LLL'); //14 F~ébrú~árý 2010 15:25 moment().fromNow(); //'á ~féw ~sécó~ñds á~gó' moment().calendar(); //'T~ódá~ý át 02:00'
Customize
Moment.js is very easy to customize. In general, you should create a locale setting with your customizations.
moment.locale('en-my-settings', { // customizations. });
You can remove a previously defined locale by passing
null
as the second argument. The deleted locale will no longer be available for use.moment.locale('fr'); // 'fr' moment.locale('en'); // 'en' moment.locale('fr', null); moment.locale('fr'); // 'en'
As of 2.12.0 it is possible to create a locale that inherits from a parent locale.
moment.defineLocale('en-foo', { parentLocale: 'en', /* */ });
Properties that are not specified in the locale will be inherited from the parent locale.
As of 2.16.0 it is possible to define a locale with a parent that hasn't itself been defined or loaded.
moment.defineLocale('fakeLocale', {parentLocale:'xyz'})
As of 2.21.0 when attempting to create a moment with the newly defined locale, moment will attempt to lazy load the parent if it exists. Failing that it will default the parent to the global locale.
As of 2.12.0 it is also possible to update a locale's properties.
moment.updateLocale('en', { /**/ });
Any properties specified will be updated, while others will remain the same. This function does not affect moments that already exist. Note that calling
updateLocale
also changes the current global locale, to the locale that is updated; see this GitHub issue for more information.To revert an update use:
moment.updateLocale('en', null);
2.12.0 deprecated using
moment.locale()
to change an existing locale. Use moment.updateLocale()
instead.Month Names 1.0.0+
// From 2.12.0 onward moment.updateLocale('en', { months : String[] }); moment.updateLocale('en', { months : Function }); moment.updateLocale('en', { months : { format : String[], standalone : String[] } }); // From 2.11.0 moment.locale('en', { months : { format : String[], standalone : String[] } }); // From 2.8.1 to 2.11.2 moment.locale('en', { months : String[] }); moment.locale('en', { months : Function }); // Deprecated in 2.8.1 moment.lang('en', { months : String[] }); moment.lang('en', { months : Function });
Locale#months
should be an array of the month names.moment.updateLocale('en', { months : [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] });
If you need more processing to calculate the name of the month, (for example, if there is different grammar for different formats),
Locale#months
can be a function with the following signature. It should always return a month name.moment.updateLocale('en', { months : function (momentToFormat, format) { // momentToFormat is the moment currently being formatted // format is the formatting string if (/^MMMM/.test(format)) { // if the format starts with 'MMMM' return nominative[momentToFormat.month()]; } else { return subjective[momentToFormat.month()]; } } });
From version 2.11.0 months can also be an object, specifying
standalone
and format
forms (nominative and accusative). The regular expression that is run on the format to check whether to use the format
form is /D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/
. From version 2.14.0 a different one can be specified with the isFormat
key.moment.updateLocale('en', { months : { format: 'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split('_'), standalone: 'sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis'.split('_'), isFormat: /D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?|MMMM?(\[[^\[\]]*\]|\s+)+D[oD]?/ // from 2.14.0 } });
Month Abbreviations 1.0.0+
// From 2.12.0 onward moment.updateLocale('en', { monthsShort : String[] }); moment.updateLocale('en', { monthsShort : Function }); moment.updateLocale('en', { monthsShort : { format: String[], standalone : String[] } }); // From 2.11.0 moment.locale('en', { monthsShort : { format: String[], standalone : String[] } }); // From 2.8.1 to 2.11.2 moment.locale('en', { monthsShort : String[] }); moment.locale('en', { monthsShort : Function }); // Deprecated in 2.8.1 moment.lang('en', { monthsShort : String[] }); moment.lang('en', { monthsShort : Function });
Locale#monthsShort
should be an array of the month abbreviations.moment.updateLocale('en', { monthsShort : [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] });
Like
Locale#months
, Locale#monthsShort
can be a callback function as well.moment.updateLocale('en', { monthsShort : function (momentToFormat, format) { if (/^MMMM/.test(format)) { return nominative[momentToFormat.month()]; } else { return subjective[momentToFormat.month()]; } } });
Note: From version 2.11.0, like
Locale#months
, Locale#monthsShort
can be an object with standalone
and format
cases.moment.updateLocale('en', { monthsShort : { format: 'янв_фев_мар_апр_мая_июня_июля_авг_сен_окт_ноя_дек'.split('_'), standalone: 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_') } });
Weekday Names 1.0.0+
// From version 2.12.0 onward moment.updateLocale('en', { weekdays : String[] }); moment.updateLocale('en', { weekdays : Function }); moment.updateLocale('en', { weekdays : { standalone : String[], format : String[], isFormat : RegExp } }); // From version 2.11.0 moment.locale('en', { weekdays : { standalone : String[], format : String[], isFormat : Boolean } }); // From version 2.8.1 to 2.11.2 moment.locale('en', { weekdays : String[] }); moment.locale('en', { weekdays : Function }); // Deprecated version 2.8.1 moment.lang('en', { weekdays : String[] }); moment.lang('en', { weekdays : Function });
Locale#weekdays
should be an array of the weekdays names.moment.updateLocale('en', { weekdays : [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ] });
Locale#weekdays
can be a callback function as well.moment.updateLocale('en', { weekdays : function (momentToFormat, format) { return weekdays[momentToFormat.day()]; } });
Note: From version 2.11.0 format/standalone cases can be passed as well.
isFormat
will be used against the full format string to determine which form to use.moment.updateLocale('en', { weekdays : { standalone: 'Воскресенье_Понедельник_Вторник_Среда_Четверг_Пятница_Суббота'.split('_'), format: 'Воскресенье_Понедельник_Вторник_Среду_Четверг_Пятницу_Субботу'.split('_'), isFormat: /\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/ } });
Weekday Abbreviations 1.0.0+
// From 2.12.0 onward moment.updateLocale('en', { weekdaysShort : String[] }); moment.updateLocale('en', { weekdaysShort : Function }); // From 2.8.1 to 2.11.2 moment.locale('en', { weekdaysShort : String[] }); moment.locale('en', { weekdaysShort : Function }); // Deprecated in 2.8.1 moment.lang('en', { weekdaysShort : String[] }); moment.lang('en', { weekdaysShort : Function });
Locale#weekdaysShort
should be an array of the weekdays abbreviations.moment.updateLocale('en', { weekdaysShort : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] });
Locale#weekdaysShort
can be a callback function as well.moment.updateLocale('en', { weekdaysShort : function (momentToFormat, format) { return weekdaysShort[momentToFormat.day()]; } });
Minimal Weekday Abbreviations 1.7.0+
// From 2.12.0 onward moment.updateLocale('en', { weekdaysMin : String[] }); moment.updateLocale('en', { weekdaysMin : Function }); // From 2.8.1 to 2.11.2 moment.locale('en', { weekdaysMin : String[] }); moment.locale('en', { weekdaysMin : Function }); // Deprecated in 2.8.1 moment.lang('en', { weekdaysMin : String[] }); moment.lang('en', { weekdaysMin : Function });
Locale#weekdaysMin
should be an array of two letter weekday abbreviations. The purpose of these is for things like calendar pickers, thus they should be as small as possible.moment.updateLocale('en', { weekdaysMin : ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] });
Locale#weekdaysMin
can be a callback function as well.moment.updateLocale('en', { weekdaysMin : function (momentToFormat, format) { return weekdaysMin[momentToFormat.day()]; } });
Long Date Formats 1.1.0+
// From 2.12.0 onward moment.updateLocale('en', { weekdaysMin : String[] }); moment.updateLocale('en', { weekdaysMin : Function }); // From 2.8.1 to 2.11.2 moment.locale('en', { longDateFormat : Object }); // Deprecated in 2.8.1 moment.lang('en', { longDateFormat : Object });
Locale#longDateFormat
should be an object containing a key/value pair for each long date format L LL LLL LLLL LT LTS
. LT
should be the time format, and is also used for moment#calendar
.moment.updateLocale('en', { longDateFormat : { LT: "h:mm A", LTS: "h:mm:ss A", L: "MM/DD/YYYY", l: "M/D/YYYY", LL: "MMMM Do YYYY", ll: "MMM D YYYY", LLL: "MMMM Do YYYY LT", lll: "MMM D YYYY LT", LLLL: "dddd, MMMM Do YYYY LT", llll: "ddd, MMM D YYYY LT" } });
You can eliminate the lowercase
l
tokens and they will be created automatically by replacing long tokens with the short token variants.moment.updateLocale('en', { longDateFormat : { LT: "h:mm A", LTS: "h:mm:ss A", L: "MM/DD/YYYY", LL: "MMMM Do YYYY", LLL: "MMMM Do YYYY LT", LLLL: "dddd, MMMM Do YYYY LT" } });
Relative Time 1.0.0+
// From 2.12.0 onward moment.updateLocale('en', { relativeTime : Object }); // From 2.8.1 to 2.11.2 moment.locale('en', { relativeTime : Object }); // Deprecated in 2.8.1 moment.lang('en', { relativeTime : Object });
Locale#relativeTime
should be an object of the replacement strings for moment#from
.moment.updateLocale('en', { relativeTime : { future: "in %s", past: "%s ago", s : 'a few seconds', ss : '%d seconds', m: "a minute", mm: "%d minutes", h: "an hour", hh: "%d hours", d: "a day", dd: "%d days", w: "a week", ww: "%d weeks", M: "a month", MM: "%d months", y: "a year", yy: "%d years" } });
Locale#relativeTime.future
refers to the prefix/suffix for future dates, and Locale#relativeTime.past
refers to the prefix/suffix for past dates. For all others, a single character refers to the singular, and a double character refers to the plural.If a locale requires additional processing for a token, it can set the token as a function with the following signature. The function should return a string.
function (number, withoutSuffix, key, isFuture) { return string; }
The
key
argument refers to the replacement key in the Locale#relativeTime
object. (eg. s m mm h
, etc.)The
number
argument refers to the number of units for that key. For m
, the number is the number of minutes, etc.The
withoutSuffix
argument will be true if the token will be displayed without a suffix, and false if it will be displayed with a suffix. (The reason for the inverted logic is because the default behavior is to display with the suffix.)The
isFuture
argument will be true if it is going to use the future suffix/prefix and false if it is going to use the past prefix/suffix.Note: Handling for
w
and ww
was added in 2.25.0.AM/PM 1.6.0+
// From 2.12.0 onward moment.updateLocale('en', { meridiem : Function }); // From 2.8.1 to 2.11.2 moment.locale('en', { meridiem : Function }); // Deprecated in 2.8.1 moment.lang('en', { meridiem : Function });
If your locale uses 'am/pm',
Locale#meridiem
can be omitted, as those values are the defaults.If your locale needs any different computation for am/pm,
Locale#meridiem
should be a callback function that returns the correct string based on hour, minute, and upper/lowercase.moment.updateLocale('zh-cn', { meridiem : function (hour, minute, isLowercase) { if (hour < 9) { return "早上"; } else if (hour < 11 && minute < 30) { return "上午"; } else if (hour < 13 && minute < 30) { return "中午"; } else if (hour < 18) { return "下午"; } else { return "晚上"; } } });
AM/PM Parsing 2.1.0+
// From 2.12.0 onward moment.updateLocale('en', { meridiemParse : RegExp isPM : Function }); // From 2.8.1 to 2.11.2 moment.locale('en', { meridiemParse : RegExp isPM : Function }); // Deprecated in 2.8.1 moment.lang('en', { meridiemParse : RegExp isPM : Function });
Locale#isPM
should return true if the input string is past 12 noon. This is used in parsing the a A
tokens.moment.updateLocale('en', { isPM : function (input) { return ((input + '').toLowerCase()[0] === 'p'); } });
To configure what strings should be parsed as input, set the
meridiemParse
property.moment.updateLocale('en', { meridiemParse : /[ap]\.?m?\.?/i });
Calendar 1.3.0+
// From 2.12.0 onward moment.updateLocale('en', { calendar : Object }); // From 2.8.1 to 2.11.2 moment.locale('en', { calendar : Object }); // Deprecated in 2.8.1 moment.lang('en', { calendar : Object });
Locale#calendar
should have the following formatting strings.moment.locale('en', { calendar : { lastDay : '[Yesterday at] LT', sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', lastWeek : '[last] dddd [at] LT', nextWeek : 'dddd [at] LT', sameElse : 'L' } });
Each of the
Locale#calendar
keys can also be a callback function with the scope of the current moment and first argument a moment that depicts now. It should return a formatting string.function callback (now) { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }
Calendar Format 2.14.0+
moment.calendarFormat = Function
This lets you modify the tokens used by calendar.
moment.calendarFormat = function (myMoment, now) { var diff = myMoment.diff(now, 'days', true); var nextMonth = now.clone().add(1, 'month'); var retVal = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : // introduce thisMonth and nextMonth (myMoment.month() === now.month() && myMoment.year() === now.year()) ? 'thisMonth' : (nextMonth.month() === myMoment.month() && nextMonth.year() === myMoment.year()) ? 'nextMonth' : 'sameElse'; return retVal; };
Ordinal 1.0.0+
// From 2.12.0 onward moment.updateLocale('en', { ordinal : Function }); // From 2.8.1 to 2.11.2 moment.locale('en', { ordinal : Function }); // Deprecated in 2.8.1 moment.lang('en', { ordinal : Function });
Locale#ordinal
should be a function that returns the ordinal for a given number.moment.updateLocale('en', { ordinal : function (number, token) { var b = number % 10; var output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } });
As of 2.0.0, the ordinal function should return both the number and the ordinal. Previously, only the ordinal was returned.
As of 2.1.0, the token parameter was added. It is a string of the token that is being ordinalized, for example:
M
or d
.For more information on ordinal numbers, see Wikipedia.
Relative Time Thresholds 2.7.0+
moment.relativeTimeThreshold(unit); // getter moment.relativeTimeThreshold(unit, limit); // setter
duration.humanize
has thresholds which define when a unit is considered a minute, an hour and so on. For example, by default more than 45 seconds is considered a minute, more than 22 hours is considered a day and so on. To change those cutoffs use moment.relativeTimeThreshold(unit, limit)
where unit is one of ss
, s
, m
, h
, d
, w
, M
.unit | meaning | usage |
ss | a few seconds | least number of seconds to be counted in seconds, minus 1. Must be set after setting the `s` unit or without setting the `s` unit. |
s | seconds | least number of seconds to be considered a minute. |
m | minutes | least number of minutes to be considered an hour. |
h | hours | least number of hours to be considered a day. |
d | days | least number of days to be considered a week. |
w | weeks | least number of weeks to be considered a month. Not used by default. |
M | months | least number of months to be considered a year. |
// Retrieve existing thresholds moment.relativeTimeThreshold('ss'); // 44 moment.relativeTimeThreshold('s'); // 45 moment.relativeTimeThreshold('m'); // 45 moment.relativeTimeThreshold('h'); // 22 moment.relativeTimeThreshold('d'); // 26 moment.relativeTimeThreshold('w'); // null (disabled) moment.relativeTimeThreshold('M'); // 11 // Set new thresholds moment.relativeTimeThreshold('s', 40); moment.relativeTimeThreshold('ss', 3); moment.relativeTimeThreshold('m', 40); moment.relativeTimeThreshold('h', 20); moment.relativeTimeThreshold('d', 25); moment.relativeTimeThreshold('w', 4); // enables weeks moment.relativeTimeThreshold('M', 10);
Note: Week unit was added in 2.25.0. By default it is not used (set to null), but you can set it to non-null value, and also (optionally) set
d
lower, so it transitions from days to weeks earlier.Note: Retrieving thresholds was added in 2.8.1.
Note: Retrieving and setting
ss
threshold was added in 2.18.0.Relative Time Rounding 2.14.0+
moment.relativeTimeRounding(); // getter moment.relativeTimeRounding(fn); // setter
duration.humanize
rounds a possibly double value before supplying it to the relativeTime format string specified in the locale. To control the rounding you can use moment.relativeTimeRounding
.var roundingDefault = moment.relativeTimeRounding(); // Round relative time evaluation down moment.relativeTimeRounding(Math.floor); moment.relativeTimeThreshold('s', 60); moment.relativeTimeThreshold('m', 60); moment.relativeTimeThreshold('h', 24); moment.relativeTimeThreshold('d', 7); moment.relativeTimeThreshold('w', 4); moment.relativeTimeThreshold('M', 12); var a = moment(); a.subtract({hours: 23, minutes: 59, seconds: 59}); a.toNow(); // == 'in 23 hours' 'Round down towards the nearest hour' // back to default moment.relativeTimeRounding(roundingDefault);
You can even choose to do no rounding at all:
var retainValue = function (value) { return value; }; moment.relativeTimeRounding(retainValue); var a = moment(); a.subtract({hours: 39}); a.toNow(); // == 'in 1.625 days', 'Round down towards the nearest year'
Changing Time Source 2.11.0+
moment.now = function () { return +new Date(); }
If you want to change the time that Moment sees, you can specify a method that returns the number of milliseconds since the Unix epoch (January 1, 1970).
The default is:
moment.now = function () { return +new Date(); }
This will be used when calling
moment()
, and the current date used when tokens are omitted from format()
. In general, any method that needs the current time uses this under the hood.First Day of Week and First Week of Year 1.0.0+
// From 2.12.0 onward moment.updateLocale('en', { week : { dow : Int, doy : Int } }); // From 2.8.1 to 2.11.2 moment.locale('en', { week : { dow : Int, doy : Int } }); // Deprecated in 2.8.1 moment.lang('en', { week : { dow : Int, doy : Int } });
Locale#week.dow
should be an integer representing the first day of the week, 0 is Sunday, 1 is Monday, ..., 6 is Saturday.Locale#week.doy
should be an integer. doy
is used together with dow
to determine the first week of the year. doy
is calculated as 7 + dow - janX
, where janX
is the first day of January that must belong to the first week of the year.// ISO-8601, Europe moment.updateLocale("en", { week: { dow: 1, // First day of week is Monday doy: 4 // First week of year must contain 4 January (7 + 1 - 4) }}); // US, Canada moment.updateLocale("en", { week: { dow: 0, // First day of week is Sunday doy: 6 // First week of year must contain 1 January (7 + 0 - 1) }}); // Many Arab countries moment.updateLocale("en", { week: { dow: 6, // First day of week is Saturday doy: 12 // First week of year must contain 1 January (7 + 6 - 1) }}); // Also common moment.updateLocale("en", { week: { dow: 1, // First day of week is Monday doy: 7 // First week of year must contain 1 January (7 + 1 - 1) }});
Eras 2.25.0+
moment.updateLocale('en', { eras: [{ since: '0001-01-01', until: +Infinity, offset: 1, name: 'Anno Domini', narrow: 'AD', abbr: 'AD' }, { until: -Infinity, since: '0000-12-31', offset: 1, name: 'Before Christ', narrow: 'BC', abbr: 'BC' }], });
Specify Eras for a particular locale. An era is a time interval with name and year numbering. Absolute year number (like 2020) can also be specified as 2020 AD: the 2020th year of the era AD. Similarly the absolute year number -0500 can be described as 501 BC, the 501st year from the BC era.
eras: [{ since: '0001-01-01', // the start of the era until: +Infinity, // the end of the era, can be +/-Infinity offset: 1, // added to year to (mostly) avoid 0 era years name: 'Anno Domini',// full name of era narrow: 'AD', // narrow name of era abbr: 'AD' // abbreviated name of era }]
since
and until
govern the direction of the era. As in the case of BC
it grows toward -Infinity
, thus since
> until
. For eras that increment toward +Infinity since
< until
.Parsing/formatting of eras is accomplished with
yo
, y*
and N*
tokens.Note: The era-related APIs are subject to change.
Invalid Date 2.3.0+
// From 2.12.0 onward moment.updateLocale('en', { invalidDate : String }); // From 2.8.1 to 2.11.2 moment.locale('en', { invalidDate : String }); // Deprecated in 2.8.1 moment.lang('en', { invalidDate : String });
Locale#invalidDate
should be a string.moment.updateLocale("es", { invalidDate: "Fecha invalida" });
Durations
Moment.js also has duration objects. Where a moment is defined as a single point in time, a duration is defined as a length of time.
Durations do not have a defined beginning and end date. They are contextless.
A duration is conceptually more similar to '2 hours' than to 'between 2 and 4 pm today'. As such, they are not a good solution to converting between units that depend on context.
For example, a year can be defined as 366 days, 365 days, 365.25 days, 12 months, or 52 weeks. Trying to convert years to days makes no sense without context. It is much better to use
moment#diff
for calculating days or years between two moments than to use Durations
.As discussed here, the duration format for Moment.js differs very slightly from the specifications for ISO 8601 nominal duration and RFC 5545 duration.
Creating 1.6.0+
moment.duration(Number, String); moment.duration(Number); moment.duration(Object); moment.duration(String); moment.duration(String, String); // 2.25.0
To create a duration, call
moment.duration()
with the length of time in milliseconds.moment.duration(100); // 100 milliseconds
If you want to create a moment with a unit of measurement other than milliseconds, you can pass the unit of measurement as well.
moment.duration(2, 'seconds'); moment.duration(2, 'minutes'); moment.duration(2, 'hours'); moment.duration(2, 'days'); moment.duration(2, 'weeks'); moment.duration(2, 'months'); moment.duration(2, 'years'); moment.duration('2', 'years'); // from 2.25.0
The same shorthand for
moment#add
and moment#subtract
works here as well.Key | Shorthand |
years | y |
months | M |
weeks | w |
days | d |
hours | h |
minutes | m |
seconds | s |
milliseconds | ms |
Much like
moment#add
, you can pass an object of values if you need multiple different units of measurement.moment.duration({ seconds: 2, minutes: 2, hours: 2, days: 2, weeks: 2, months: '2', years: '2' });
As of 2.1.0, moment supports parsing ASP.NET style time spans. The following formats are supported.
The format is an hour, minute, second string separated by colons like
23:59:59
. The number of days can be prefixed with a dot separator like so 7.23:59:59
. Partial seconds are supported as well 23:59:59.999
.moment.duration('23:59:59'); moment.duration('23:59:59.999'); moment.duration('7.23:59:59.999'); moment.duration('23:59'); // added in 2.3.0
As of 2.3.0, moment also supports parsing ISO 8601 durations.
moment.duration('P1Y2M3DT4H5M6S'); moment.duration('P1M');
As of 2.11.0, duration format strings with a space between days and rest is supported.
moment.duration('7 23:59:59.999');
As of 2.13.0, mixed negative and positive signs are supported when parsing durations.
moment.duration('PT-6H3M')
As of 2.18.0, invalid durations are supported, similarly to invalid moments. To create an invalid duration you can pass
NaN
for a value of a unit.In upcoming releases expect invalid durations to cover more cases (like null values for units).
moment.duration(NaN); moment.duration(NaN, 'days'); moment.duration.invalid();
Clone 2.19.0+
moment.duration().clone();
Create a clone of a duration. Durations are mutable, just like moment objects, so this lets you get a snapshot, at some point in time.
var d1 = moment.duration(); var d2 = d1.clone(); d1.add(1, 'second'); d1.asMilliseconds() !== d2.asMilliseconds();
Humanize 1.6.0+
moment.duration().humanize(); moment.duration().humanize(withSuffix); moment.duration().humanize(withSuffix, thresholds); // from 2.25.0 moment.duration().humanize(thresholds); // from 2.25.0
Sometimes, you want all the goodness of
moment#from
but you don't want to have to create two moments, you just want to display a length of time.Enter
moment.duration().humanize()
.moment.duration(1, "minutes").humanize(); // a minute moment.duration(2, "minutes").humanize(); // 2 minutes moment.duration(24, "hours").humanize(); // a day
By default, the return string is describing a duration
a month
(suffix-less). If you want an oriented duration in a month
, a month ago
(with suffix), pass in true as seen below.moment.duration(1, "minutes").humanize(true); // in a minute
For suffixes before now, pass in a negative number.
moment.duration(-1, "minutes").humanize(true); // a minute ago
Invalid durations are humanized to the localized version of
Invalid Date
.moment.duration.invalid().humanize(); // Invalid Date
Humanize output can be configured with relative time thresholds. To specify thresholds for a particular invocation of humanize, pass them as a sole argument or after suffix arg:
moment.duration(-1, 'week').humanize(true, {d: 7, w: 4}); // a week ago moment.duration(-1, 'week').humanize({d: 7, w: 4}); // a week
Note: Passing thresholds in humanize was added in 2.25.0.
Milliseconds 1.6.0+
moment.duration().milliseconds(); moment.duration().asMilliseconds();
To get the number of milliseconds in a duration, use
moment.duration().milliseconds()
.It will return a number between 0 and 999.
moment.duration(500).milliseconds(); // 500 moment.duration(1500).milliseconds(); // 500 moment.duration(15000).milliseconds(); // 0
If you want the length of the duration in milliseconds, use
moment.duration().asMilliseconds()
instead.moment.duration(500).asMilliseconds(); // 500 moment.duration(1500).asMilliseconds(); // 1500 moment.duration(15000).asMilliseconds(); // 15000
Seconds 1.6.0+
moment.duration().seconds(); moment.duration().asSeconds();
To get the number of seconds in a duration, use
moment.duration().seconds()
.It will return a number between 0 and 59.
moment.duration(500).seconds(); // 0 moment.duration(1500).seconds(); // 1 moment.duration(15000).seconds(); // 15
If you want the length of the duration in seconds, use
moment.duration().asSeconds()
instead.moment.duration(500).asSeconds(); // 0.5 moment.duration(1500).asSeconds(); // 1.5 moment.duration(15000).asSeconds(); // 15
Minutes 1.6.0+
moment.duration().minutes(); moment.duration().asMinutes();
As with the other getters for durations,
moment.duration().minutes()
gets the minutes (0 - 59).moment.duration().asMinutes()
gets the length of the duration in minutes.Hours 1.6.0+
moment.duration().hours(); moment.duration().asHours();
As with the other getters for durations,
moment.duration().hours()
gets the hours (0 - 23).moment.duration().asHours()
gets the length of the duration in hours.Days 1.6.0+
moment.duration().days(); moment.duration().asDays();
As with the other getters for durations,
moment.duration().days()
gets the days (0 - 30).moment.duration().asDays()
gets the length of the duration in days.Weeks 1.6.0+
moment.duration().weeks(); moment.duration().asWeeks();
As with the other getters for durations,
moment.duration().weeks()
gets the weeks (0 - 4).moment.duration().asWeeks()
gets the length of the duration in weeks.Pay attention that unlike the other getters for duration, weeks are counted as a subset of the days, and are not taken off the days count.
Note: The length of a duration in weeks is defined as 7 days.
Months 1.6.0+
moment.duration().months(); moment.duration().asMonths();
As with the other getters for durations,
moment.duration().months()
gets the months (0 - 11).moment.duration().asMonths()
gets the length of the duration in months.Years 1.6.0+
moment.duration().years(); moment.duration().asYears();
As with the other getters for durations,
moment.duration().years()
gets the years.moment.duration().asYears()
gets the length of the duration in years.Add Time 2.1.0+
moment.duration().add(Number, String); moment.duration().add(Number); moment.duration().add(Duration); moment.duration().add(Object);
Mutates the original duration by adding time.
The same keys and shorthands used to create durations can be used here as the second argument.
var a = moment.duration(1, 'd'); var b = moment.duration(2, 'd'); a.add(b).days(); // 3
Note that adding an invalid duration to any other duration results in an invalid duration.
Subtract Time 2.1.0+
moment.duration().subtract(Number, String); moment.duration().subtract(Number); moment.duration().subtract(Duration); moment.duration().subtract(Object);
Mutates the original duration by subtracting time.
The same keys and shorthands used to create durations can be used here as the second argument.
var a = moment.duration(3, 'd'); var b = moment.duration(2, 'd'); a.subtract(b).days(); // 1
Note that adding an invalid duration to any other duration results in an invalid duration.
Using Duration with Diff 2.1.0+
var duration = moment.duration(x.diff(y))
You can also use duration with
moment#diff
to get the duration between two moments. To do so, simply pass the moment#diff
method into moment#duration
as follows:var x = new moment() var y = new moment() var duration = moment.duration(x.diff(y)) // returns duration object with the duration between x and y
See here for more information about
moment#diff
.As Unit of Time 2.1.0+
moment.duration().as(String);
As an alternate to
Duration#asX
, you can use Duration#as('x')
. All the shorthand keys from moment#add
apply here as well.duration.as('hours'); duration.as('minutes'); duration.as('seconds'); duration.as('milliseconds');
Invalid durations return
NaN
for all units.Get Unit of Time 2.1.0+
moment.duration().get(String);
As an alternate to
Duration#x()
getters, you can use Duration#get('x')
. All the shorthand keys from moment#add
apply here as well.duration.get('hours'); duration.get('minutes'); duration.get('seconds'); duration.get('milliseconds');
Invalid durations return
NaN
for all units.As JSON 2.9.0+
moment.duration().toJSON();
When serializing a duration object to JSON, it will be represented as an ISO8601 string.
JSON.stringify({ postDuration : moment.duration(5, 'm') }); // '{"postDuration":"PT5M"}'
Invalid durations return
Invalid Date
as json representation.Is a Duration 1.6.0+
moment.isDuration(obj);
To check if a variable is a moment duration object, use
moment.isDuration()
.moment.isDuration() // false moment.isDuration(new Date()) // false moment.isDuration(moment()) // false moment.isDuration(moment.duration()) // true moment.isDuration(moment.duration(2, 'minutes')) // true
As ISO 8601 String 2.8.0+
moment.duration().toISOString();
Returns duration in string as specified by ISO 8601 standard.
moment.duration(1, 'd').toISOString() // "P1D"
Format
PnYnMnDTnHnMnS
description:Unit | Meaning |
P | _P_ stands for period. Placed at the start of the duration representation. |
Y | Year |
M | Month |
D | Day |
T | Designator that precedes the time components. |
H | Hour |
M | Minute |
S | Second |
Locale 2.17.1+
moment.duration().locale(); moment.duration().locale(String);
You can get or set the locale of a duration using
locale(...)
. The locale will affect the duration's string methods, like humanize()
. See the intl section for more information on internationalization generally.moment.duration(1, "minutes").locale("en").humanize(); // a minute moment.duration(1, "minutes").locale("fr").humanize(); // une minute moment.duration(1, "minutes").locale("es").humanize(); // un minuto
Suffixes in
humanize()
are also internationalized:moment.duration(1, "minutes").locale("en").humanize(true); // in a minute moment.duration(1, "minutes").locale("fr").humanize(true); // dans une minute moment.duration(1, "minutes").locale("es").humanize(true); // en un minuto moment.duration(-1, "minutes").locale("en").humanize(true); // a minute ago moment.duration(-1, "minutes").locale("fr").humanize(true); // il y a une minute moment.duration(-1, "minutes").locale("es").humanize(true); // hace un minuto
Utilities
Moment exposes some methods which may be useful to people extending the library or writing custom parsers.
Normalize Units 2.3.0+
moment.normalizeUnits(String);
Many of Moment's functions allow the caller to pass in aliases for unit enums. For example, all of the
get
s below are equivalent.var m = moment(); m.get('y'); m.get('year'); m.get('years');
If you're extending the library, you may want access to Moment's facilities for that in order to better align your functionality with Moment's.
moment.normalizeUnits('y'); // 'year' moment.normalizeUnits('Y'); // 'year' moment.normalizeUnits('year'); // 'year' moment.normalizeUnits('years'); // 'year' moment.normalizeUnits('YeARS'); // 'year'
Invalid 2.3.0+
moment.invalid(Object);
You can create your own invalid Moment objects, which is useful in making your own parser.
var m = moment.invalid(); m.isValid(); // false m.format(); // 'Invalid date' m.parsingFlags().userInvalidated; // true
invalid
also accepts an object which specifies which parsing flags to set. This will not set the userInvalidated
parsing flag unless it's one of the properties specified.var m = moment.invalid({invalidMonth: 'Actober'}); m.parsingFlags().invalidMonth; // 'Actober'
You need not specify parsing flags recognized by Moment; the Moment will be invalid nonetheless, and the parsing flags will be returned by
parsingFlags()
.Plugins
Some other people have made plugins for Moment.js that may be useful to you.
Strftime
npm install moment-strftime
If you are more comfortable working with strftime instead of LDML-like parsing tokens, you can use Ben Oakes' plugin
moment-strftime
.The repository is located at github.com/benjaminoakes/moment-strftime.
MSDate
If you are using OLE Automation dates in .NET check out Markit On Demand's
moment-msdate
. Using this plugin allows you to format OA dates into JavaScript dates and vice-versa.Convert a
moment
to an OA date:moment().toOADate(); // a floating point number
Or, convert an OA date to a
moment
:moment.fromOADate(41493); // Wed Aug 07 2013 00:00:00 GMT-0600 (MDT)
More information and detailed docs can be found on GitHub at http://markitondemand.github.io/moment-msdate/.
Java DateFormat Parser
npm install moment-jdateformatparser
If you want to work with the
java.text.DateFormat
you can use this plugin.For example,
moment("2013-12-24 14:30").formatWithJDF("dd.MM.yyyy"); // returns the formatted date "24.12.2013" moment().toJDFString("DD.MM.YYYY"); // returns the Java format pattern "dd.MM.yyyy"
The repository is located at github.com/MadMG/moment-jdateformatparser.
Date Ranges
npm install moment-range
If you need to work with date ranges, you can use Gianni Chiappetta's plugin
moment-range
.Documentation can be found on the homepage github.com/rotaready/moment-range.
And it is also available for the web at the repository below.
The repository is located at github.com/rotaready/moment-range.
Twix
npm install twix
Another range plugin is Isaac Cambron's library
Twix
. It has many range-related features and excels at formatting ranges readably. For example,var t = moment("1/25/1982 9:30 AM").twix("1/25/1982 1:30 PM"); t.isCurrent(); // false t.count('minutes'); // 241 t.format(); // 'Jan 25, 1982, 9:30 AM - 1:30 PM' t.simpleFormat("h:m"); // '9:30 - 1:30'
Full documentation of all the options and features is here.
It's available on npm like so:
npm install twix
Or just grab the JS file from here.
Precise Range
npm install moment-precise-range-plugin
The Precise Range plugin, written by Rob Dawson, can be used to display exact, human-readable representations of date/time ranges:
moment("2014-01-01 12:00:00").preciseDiff("2015-03-04 16:05:06"); // 1 year 2 months 3 days 4 hours 5 minutes 6 seconds
moment.preciseDiff("2014-01-01 12:00:00", "2014-04-20 12:00:00"); // 3 months 19 days
To obtain the raw numeric values rather than a string, pass the value
true
as the third argument to the method:moment.preciseDiff(m1, m2, true); // {years : 0, months : 1, days : 2, hours : 3, minutes : 4, seconds : 5, firstDateWasLater : false}
ISO Calendar
npm install moment-isocalendar
If you are looking for a Python-like isocalendar method, you can use Rocky Meza's plugin
moment-isocalendar
Calling the isocalendar method on a moment will return an array like the following:
[year, week_of_year, day_of_week, minutes_since_midnight]
moment().isocalendar(); // [2012, 8, 5, 870]
You can also reconstruct a moment from a isocalendar array.
moment.fromIsocalendar([2011, 51, 5, 870]).format('LLLL'); // "Friday, December 23 2011 2:30 PM"
The repository is located at github.com/fusionbox/moment-isocalendar.
Jalaali Calendar
npm install moment-jalaali
If you want to work with Jalaali calendar system (Jalali, Persian, Khorshidi or Shamsi), you can use Behrang Noruzi Niya's plugin
moment-jalaali
.When installed, it will wrap
moment
and moment will be able to format and parse Jalaali years and months. Here is a short example:var m = moment('1360/5/26', 'jYYYY/jM/jD'); // Parse a Jalaali date. m.format('jYYYY/jM/jD [is] YYYY/M/D'); // 1360/5/26 is 1981/8/17
The repository is located at github.com/behrang/moment-jalaali.
Hijri Calendar
npm install moment-hijri
If you want to work with Hijri calendar then you can use
moment-hijri
plugin. moment-hijri
is a moment plugin for the Hijri lunar calendar based on Umm al-Qura calculations. This plugin is developed by Suhail Alkowaileet.When you install it, it will wrap
moment
and you will be able to parse Hijri dates. Here is a short example:m = moment('1410/8/28', 'iYYYY/iM/iD'); // Parse a Hijri date. m.format('iYYYY/iM/iD [is] YYYY/M/D'); // 1410/8/28 is 1990/3/25
The repository is located at github.com/xsoh/moment-hijri.
Islamic Civil Calendar
npm install moment-islamic-civil
This is another Hijri calendar (based on civil calculations).
The repository is located at github.com/ACGC/moment-islamic-civil.
Recur
npm install moment-recur
If you need to work with recurring dates, you can use Casey Trimm's plugin
moment-recur
.This plugin will allow you to create length-based intervals (days, weeks, etc.) and calendar-based intervals (daysOfMonth, monthsOfYear, etc.).
It provides a
matches
function to test whether a date recurs according to the rules set, as well as generator functions to get the next and previous dates in a series.The repository, documentation, and many more examples can be found at github.com/c-trimm/moment-recur
var interval = moment( "01/01/2014" ).recur().every(2).days(); // Length Interval interval.matches( "01/03/2014" ); // true interval.next( 2, "L" ); // ["01/03/2014", "01/05/2014"] interval.forget( "days" ); // Remove a rule interval.dayOfMonth( 10 ); // Calendar Interval interval.matches( "05/10/2014" ); // true interval.previous( 2, "L" ); // ["12/10/2013", "11/10/2013"]
If you're trying to format times for tweets like the way Twitter does, you can use the moment.twitter plugin by @hijonathan.
It's a simple way to display both short and long versions of human-readable timestamps.
moment().subtract(5, 'hours').twitterLong(); // 5 hours
Yes, it does smart pluralization.
moment().subtract(1, 'hour').twitterLong(); // 1 hour
Not short enough for you?
moment().subtract(6, 'days').twitterShort(); // 6d
Fiscal Quarters
If you ever have need for Fiscal, Calendar or Academic quarters, you can use the moment-fquarter plugin by @robgallen.
At its simplest, just call the fquarter method on any moment object. It returns a formatted string with April being the first quarter.
moment("2013-01-01").fquarter(); // Q4 2012/13
You can pass in any month as the starting quarter, e.g. July
moment("2013-01-01").fquarter(7); // Q3 2012/13
If you want calendar quarters, start in January
moment("2013-01-01").fquarter(1); // Q1 2013
Parse Date Format
npm install moment-parseformat
This plugin extracts the format of a date/time string.
var format = moment.parseFormat('Thursday, February 6th, 2014 9:20pm'); // dddd, MMMM Do, YYYY h:mma moment().format(format); // format
That allows to create smart date inputs that let your users set a Date/Time and lets you extract the user's preferred format for future usage. Find an example usage of it at minutes.io.
Round
npm install moment-round
This plugin will round date/time to a given interval.
For example,
require('moment-round'); var m = new moment(); // 2015-06-18 15:30:19 m.round(5, 'seconds'); // 2015-06-18 15:30:20 m.ceil(3, 'minutes'); // 2015-06-18 15:33:00 m.floor(16, 'hours'); // 2015-06-18 00:00:00 m.ceil(21, 'hours'); // 2015-06-18 21:00:00 m.ceil(20, 'hours'); // 2015-06-19 00:00:00
The repository is located at github.com/WebDevTmas/moment-round.
Transform
bower install moment-transform
moment-transform
is a plugin that manipulated dates through patterns. You can use basic operations –set/add/subtract– on individual parts (hours, month, …) of a Moment instance.moment().transform('YYYY-MM-+01 00:00:00.000'); // Tonight at midnight moment().transform('14:30:00.000'); // Today, 2:30 pm moment().transform('YYYY-MM--30 00:00:00.000'); // 30 days ago
Optional parameters lets you specify custom patterns and force strict pattern usage (non-alphabetic characters are not mandatory in passed string by default).
moment().transform('+01MMYYYY', 'DD/MM/YYYY', false); // Tomorrow, same time moment().transform('+01MMYYYY', 'DD/MM/YYYY', true); // Invalid date
Taiwan Calendar
npm install moment-taiwan
If you want to work with Taiwan calendar system , you can use Bradwoo8621's plugin
moment-taiwan
.When installed, it will wrap
moment
and moment will be able to format and parse Taiwan years. Here is a short example:m = moment('104/01/01', 'tYY/MM/DD') // Parse a Taiwan date m.format('tYY/MM/DD [is] YYYY/M/D') // 104/01/01 is 2015/01/01 m.twYear() // 104
The repository is located at github.com/bradwoo8621/moment-taiwan.
Duration Format
npm install moment-duration-format
This is a plugin that will allow comprehensive formatting of Moment Durations.
For example,
moment.duration(123, "minutes").format("h:mm"); // "2:03"
The repository is located at github.com/jsmreese/moment-duration-format.
Timer
npm install moment-timer
This is a Moment.js plugin that allows the use of timers, which offer much more control than the native JavaScript timers. It's basically a rewrite of JavaScripts own setInterval and setTimeout.
For example,
var timer = moment.duration(5, "seconds").timer({loop: true}, function() { // Callback });
The repository is located at github.com/SeverinDK/moment-timer.
Business
npm install moment-business
This is a Moment.js library that allows Moment operations for Western work weeks: 7 day weeks where Saturday and Sunday are non-work days.
For example,
import business from 'moment-business'; // true if the moment is Mon-Fri, false otherwise business.isWeekDay(someMoment); // Adds five work days to the Moment business.addWeekDays(someMoment, 5);
The repository is located at github.com/jmeas/moment-business.
Short Date Formatter
If you want to format times in a short way, you can use the moment-shortformat plugin by @researchgate.
It is based on and similar to the moment.twitter plugin but has a different output.
moment().subtract(5, 'hours').short(); // 5h ago moment().add(5, 'hours').short(); // in 5h
You can also disable the use of the relative time templates
moment().subtract(1, 'hour').short(false); // 1h
If the date is too far in the future or the past it will display like that
moment().subtract(500, 'days').short(); // 5 Mar, 1970
German Holiday (Feiertag)
npm install moment-feiertage --save
This (moment-feiertage) is a Moment.js plugin to determine if a date is a German holiday. Holidays are taken from Wikipedia (de). It's a bit complicated to determine if a date is a holiday, because religious holidays vary every year and differ within the 16 German states.
Made by DaniSchenk.
var someDateInSomeStates = moment('2018-11-01').isHoliday(['BW', 'SH', 'TH']); /* returns { allStates: false, holidayName: 'Allerheiligen', holidayStates: [ 'BW' ], testedStates: [ 'BW', 'SH', 'TH' ] }*/
The repository is located at github.com/DaniSchenk/moment-feiertage.