# 显示

back

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

# 格式化

back

moment().format();
moment().format(String);
1
2

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)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a");
// "Sunday, February 14th 2010, 3:25:50 pm"
moment().format("ddd, hA");
// "Sun, 3PM"
moment('gibberish').format('YYYY MM DD');
// "Invalid date"
1
2
3
4
5
6
7
8
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
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
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
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..]
Timezone z or zz EST CST ... MST PST,Note: as of 1.6.0, the z/zz format tokens have been deprecated. Read more about it here.
Z -07:00 -06:00 ... +06:00 +07:00
ZZ -0700 -0600 ... +0600 +0700
Unix Timestamp X 1360013296
Unix Millisecond Timestamp x 1360013296123
  • Z ZZ were added in 1.2.0.
  • S SS SSS were added in 1.6.0.
  • 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.

# Localized_formats

back

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 LT are available in version 1.3.0.
  • l ll lll llll are available in 2.0.0. LTS was added in 2.8.4.

# Escaping_characters

back

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

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

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

back

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

# Other_tokens

back

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

back

As of version 1.5.0, 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.

# 时差_之前_现在为基准

back

moment().fromNow();
moment().fromNow(Boolean);
1
2

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
1

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
1
2

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 45 seconds s a few seconds ago
45 to 90 seconds m a minute ago
90 seconds to 45 minutes mm 2 minutes ago ... 45 minutes ago
45 to 90 minutes h an hour ago
90 minutes to 22 hours hh 2 hours ago ... 22 hours ago
22 to 36 hours d a day ago
36 hours to 25 days dd 2 days ago ... 25 days ago
25 to 45 days M a month ago
45 to 345 days MM 2 months ago ... 11 months ago
345 to 545 days (1.5 years) y a year ago
546 days+ yy 2 years ago ... 20 years ago
  • From version 2.10.3, if the target moment object is invalid the result is the localized Invalid date string.

# 时差_之前

back

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

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"
1
2
3

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"
1
2
3
4
5
6

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"
1
2
3
4
  • From version 2.10.3, if any of the endpoints are invalid the result is the localized Invalid date string.

# 时差 (之后,现在为基准) 2.10.3+

moment().toNow();
moment().toNow(Boolean);
1
2

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

显示时间的常用方法由moment#toNow处理。有时称为时间间隔或相对时间。

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
1

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

如果传递true,则可以获取不带前缀的值

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

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 45 seconds s in seconds
45 to 90 seconds m in a minute
90 seconds to 45 minutes mm in 2 minutes ... in 45 minutes
45 to 90 minutes h in an hour
90 minutes to 22 hours hh in 2 hours ... in 22 hours
22 to 36 hours d in a day
36 hours to 25 days dd in 2 days ... in 25 days
25 to 45 days M in a month
45 to 345 days MM in 2 months ... in 11 months
345 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.

# 时差 (之后) 2.10.3+

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

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"
1
2
3

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"
1
2
3
4
5
6

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"
1
2
3
4

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

# 日历时间 1.3.0+

moment().calendar();
moment().calendar(referenceTime);
moment().calendar(referenceTime, formats);  // from 2.10.5
1
2
3

Calendar time displays time relative to a given referenceTime (defaults to now), but does so slightly differently than moment#fromNow.

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

moment#calendar会根据日期与referenceTime的日期(默认为今天)的接近程度,使用不同的字符串格式化日期。

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'
});
1
2
3
4
5
6
7
8

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

# 时差 (毫秒) 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);
1
2
3

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
1
2
3

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
1
2
3

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 return number rounded down. If you want the floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned rounded number, not a rounded down number.

默认情况下,moment#diff将返回四舍五入的数字。如果需要浮点数,则将true作为第三个参数传递。在2.0.0之前,moment#diff返回四舍五入的数字,而不是四舍五入的数字。

var a = moment([2008, 6]);
var b = moment([2007, 0]);
a.diff(b, 'years');       // 1
a.diff(b, 'years', true); // 1.5
1
2
3
4

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
1
2
3
4

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

考虑这一点的一种简单方法是将.diff(替换为减号运算符

          // a < b
a.diff(b) // a - b < 0
b.diff(a) // b - a > 0
1
2
3

# 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 偏移量 (毫秒) 1.0.0+

moment().valueOf();
+moment();
1
2

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

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

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

# Unix 时间戳 (秒) 1.6.0+

moment().unix();
1

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

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

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

# 天数 (月) 1.5.0+

moment().daysInMonth();
1

Get the number of days in the current month.

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

# Date 对象 1.0.0+

moment().toDate();
1

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

This will return the Date that the moment uses, so any changes to that Date will cause the moment to change. If you want a Date that is a copy, use moment#clone before you use moment#toDate.

这将返回该时刻使用的日期,因此对该日期的任何更改都将导致该时刻发生变化。如果您希望日期为副本,请在使用moment#toDate之前先使用moment#clone。

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

# 数组 1.7.0+

moment().toArray();
1

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

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

# JSON 2.0.0+

moment().toJSON();
1

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"}'
1
2
3

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(); }
1

This changes the behavior as follows:

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

# ISO 8601 字符串 2.1.0+

moment().toISOString();
1

Formats a string to the ISO8601 standard.

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

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

# 对象 2.10.5+

moment().toObject();
1

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
                     // }
1
2
3
4
5
6
7
8
9