# 解析

back

<script src="moment.js"></script>
<script>
    moment().format();
</script>
1
2
3
4

# 当前时间

back

var now = moment();//moment(new Date())一个意思
1

# 通过字符串(ISO8601)获取时间

back

var day = moment("1995-12-25");//符合ISO8601格式
1
ISO8601 含义
2013-02-08 A calendar date part
2013-W06-5 A week date part
2013-039 An ordinal date part
2013-02-08T09 An hour time part separated by a T
2013-02-08 09 An hour time part separated by a space
2013-02-08 09:30 An hour and minute time part
2013-02-08 09:30:26 An hour, minute, and second time part
2013-02-08 09:30:26.123 An hour, minute, second, and millisecond time part
2013-02-08 24:00:00.000 hour 24, minute, second, millisecond equal 0 means next day at midnight
2013-02-08 09+07:00 +-HH:mm
2013-02-08 09-0100 +-HHmm
2013-02-08 09Z Z
2013-02-08 09:30:26.123+07:00 +-HH:mm

日期时间:separated from the date part by a space or a uppercase T.
If a time part is included, an offset from UTC can also be included as +-HH:mm, +-HHmm, or Z.

# 检测是否合法

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

# 字符串+格式

back

moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);
1
2
3
4

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

解析器将忽略非字母数字字符,因此以下两个都将返回相同的内容。

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

# Year, month, and day tokens

Input Example Description
YYYY 2014 4 or 2 digit year
YY 14 2 digit year
Q 1..4 Quarter of year. Sets month to first month in quarter.
M MM 1..12 Month number
MMM MMMM Jan..December Month name in locale set by moment.locale()
D DD 1..31 Day of month
Do 1st..31st Day of month with ordinal
DDD DDDD 1..365 Day of year
X 1410715640.579 Unix timestamp
x 1410715640579 Unix ms timestamp

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

版本2.10.5的YYYY支持2位数字的年份,并将其转换为接近2000的年份(与YY相同)。

# Week year, week, and weekday tokens

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

对于这些,小写字母标记使用语言环境感知的星期开始天,而大写字母标记使用ISO星期日期开始天。

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

# Hour, minute, second, millisecond, and offset tokens

Input Example Description
H HH 0..23 24 hour time
h hh 1..12 12 hour time used with a A.
a A am pm Post or ante meridiem
m mm 0..59 Minutes
s ss 0..59 Seconds
S 0..9 Tenths of a second
SS 0..99 Hundreds of a second
SSS 0..999 Thousandths of a second
SSSS 0000..9999 fractional seconds
Z ZZ +12:00 Offset from UTC as +-HH:mm, +-HHmm, or Z

# 字符串+多个格式

back

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

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

解析多种格式比解析单一格式要慢得多。如果可以避免的话,“解析单一格式要快得多”。

# 字符串特殊格式

back

moment(String, moment.CUSTOM_FORMAT, [String], [Boolean]);
moment(String, [..., moment.ISO_8601, ...], [String], [Boolean]);
1
2
moment("2010-01-01T05:06:07", moment.ISO_8601);
moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);
1
2

# 对象

back

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

# unix偏移量

back

moment(Number);
1

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

与new Date(Number)相似,您可以通过传递一个整数值来创建时刻,该整数值表示自Unix纪元(1970年1月1日12 AM UTC)以来的毫秒数

var day = moment(1318781876406);
1

# unix时间戳

back

moment.unix(Number)
1

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

要从Unix时间戳创建时刻(自Unix纪元以来的秒数),请使用moment.unix(Number)

var day = moment.unix(1318781876);
1

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

这被实现为moment(timestamp *1000),因此在输入时间戳中包含了部分秒数。

var day = moment.unix(1318781876.721);
1

# Date对象

back

moment(Date);
1

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

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

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

这将克隆Date对象;日期的进一步更改不会影响片刻,反之亦然。

# 数组

back

moment(Number[]);
1

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

new Date();
new Date(value);
new Date(dateString);
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

[year, month, day, hour, minute, second, millisecond]
moment([2010, 1, 14, 15, 25, 50, 125]); // February 14th, 3:25:50.125 PM
1
2

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

年份之后的任何值都是可选的,并且默认为可能的最小值。

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

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

使用数组构造将在当前时区中创建一个日期。要从UTC数组创建日期,请使用moment.utc(Number [])。

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

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

如果数组表示的日期不存在,moment#isValid将返回false。

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

# 克隆

back

moment(Moment);
1

All moments are mutable. If you want a clone of a moment, you can do so explicitly or implicitly.Calling moment() on a moment will clone it.

所有的moments都是可变的。如果您想要一个moments的克隆,则可以显式或隐式地进行。在moments调用moment()将对其进行克隆。

var a = moment([2012]);
var b = moment(a);
a.year(2000);
b.year(); // 2012
1
2
3
4

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

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

# utc

back

moment.utc();
moment.utc(Number);
moment.utc(Number[]);
moment.utc(String);
moment.utc(String, String);
moment.utc(String, String[]);
moment.utc(String, String, String);
moment.utc(Moment);
moment.utc(Date);
1
2
3
4
5
6
7
8
9
moment().format();     // 2013-02-04T10:35:24-08:00
moment.utc().format(); // 2013-02-04T18:35:24+00:00
1
2

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

另外,在UTC模式下,所有的getter和setter都将在内部使用Date#getUTC*Date#setUTC *方法,而不是Date#get *Date#set *方法。

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

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

重要的是要注意,尽管上面的显示有所不同,但它们在同一时间都是相同的。

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

Any moment created with moment.utc() will be in UTC mode, and any moment created with moment() will not.To switch from UTC to local time, you can use moment#utc or moment#local.

使用moment.utc()创建的任何时刻都将处于UTC模式,而使用moment()创建的任何时刻都不会处于UTC模式。要从UTC切换到本地时间,可以使用moment#utcmoment#local

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

# 时区

back

moment.parseZone(String);
1

Moment normally interprets input times as local times (or UTC times if moment.utc() is used). However, often the input string itself contains time zone information. #parseZone parses the time and then sets the zone according to the input string.

Moment通常将输入时间解释为本地时间(如果使用moment.utc(),则解释为UTC时间)。但是,输入字符串本身通常包含时区信息。 #parseZone解析时间,然后根据输入字符串设置区域。

moment.parseZone("2013-01-01T00:00:00-13:00").zone(); // 780
1

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

moment.parseZone等效于解析字符串并使用moment#zone解析区域。

var s = "2013-01-01T00:00:00-13:00";
moment(s).zone(s);//this method only works for a single string argument, not a string and format.
1
2

# 合法性校验

back

moment().isValid();
1

Moment applies stricter initialization rules than the Date constructor.

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

You can check whether the Moment considers the date invalid using moment#isValid. You can check the metrics used by #isValid using moment#parsingFlags, which returns an object.
The following parsing flags result in an invalid date:

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

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

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

Note: Moment's concept of validity became more strict and consistent between 2.2 and 2.3.

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

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

The return value has the following meaning:

0——years
1——months
2——days
3——hours
4——minutes
5——seconds
6——milliseconds

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

如果有多个错误的单位,则返回第一个单位(例如,由于有效期可能取决于月份)。

# 默认值

back

moment("15", "hh");
1

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

您可以创建一个矩对象,只指定一些单位,其余的将默认为当前的日期,月份或年份,或者小时,分钟,秒和毫秒的默认值为0。

moment();  // current date and time
1

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

默认为今天,仅传小时,分钟,秒和毫秒时:

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

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

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

Defaulting to this year, if year is not specified:

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