7周+5天 孕囊大小是3.7*3.5*2.0 请问黄小琥是男是女女

文档 | Moment.js 中文网
Moment.js 文档
Moment was designed to work both in the browser and in Node.js.
Currently the following browsers are used for the ci system: IE8, IE9 on
Windows 7, stable Chrome on Windows XP, Safari 10.8 on Mac and stable
Firefox on Linux.
All code will work in both environments. All unit tests are run in both environments.
npm install moment
var moment = require('moment');
moment().format();
Note: In 2.4.0, the globally exported moment object was deprecated.
It will be removed in next major release.
&script src=&moment.js&&&/script&
moment().format();
Moment.js is available on . Remember though, cool kids concatenate their scripts to minimize http requests.
bower install --save moment
Notable files are moment.js, locale/*.js and min/moment-with-locales.js.
require.config({
"moment": "path/to/moment",
define(["moment"], function (moment) {
moment().format();
Moment will still create a moment global, which is useful to plugins and other third-party code. If you wish to squash that global, use the noGlobal option on the module config.
require.config({
noGlobal: true
If you don't specify noGlobal then the globally exported moment will print
a deprecation warning. From next major release you'll have to export it
yourself if you want that behavior.
For version 2.5.x, in case you use other plugins that rely on Moment but are
not AMD-compatible you may need to add
to your r.js config.
Note: To allow moment.js plugins to be loaded in requirejs environments, moment is created as a named module. Because of this, moment must be loaded exactly as as &moment&, using paths to determine the directory. Requiring moment with a path like &vendor\moment& will return undefined.
Note: From version 2.9.0 moment exports itself as an anonymous module,
so if you're using only the core (no locales / plugins), then you don't need
config if you put it on a non-standard location.
Install-Package Moment.js
spm install moment --save
meteor add momentjs:moment
To use under Java/Rhino, see .
To use in Demandware, see .
If you are having any troubles, try asking a question on
with the momentjs tag.
You can also use the
to find related issues or open a new issue.
Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object. To get this wrapper object, simply call moment() with one of the supported input types.
The Moment prototype is exposed through moment.fn. If you want to add your own functions, that is where you would put them.
For ease of reference, any method on the Moment.prototype will be referenced in the docs as moment#method. So Moment.prototype.format == moment.fn.format == moment#format.
To get the current date and time, just call moment() with no parameters.
var now = moment();
This is essentially the same as calling moment(new Date()).
moment(String);
When creating a moment from a string, we first check if the string matches known
formats, then fall back to new Date(string) if a known format is not found.
var day = moment("");
Warning: Browser support for parsing strings . Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.
For consistent results parsing anything other than ISO 8601 strings, you should use .
Supported ISO 8601 strings
An ISO 8601 string requires a date part.
# A calendar date part
# A week date part
# An ordinal date part
A time part can also be included, separated from the date part by a space or a uppercase T.
# An hour time part separated by a T
# An hour time part separated by a space
# An hour and minute time part
# An hour, minute, and second time part
09:30:26.123
# An hour, minute, second, and millisecond time part
24:00:00.000
# hour 24, minute, second, millisecond equal 0 means next day at midnight
Any of the date parts can have a time part.
# A calendar date part and hour time part
# A week date part and hour time part
# An ordinal date part and hour time part
If a time part is included, an offset from UTC can also be included as +-HH:mm, +-HHmm, or Z.
09:30:26.123+07:00
Note: Automatic cross browser ISO-8601 support was added in version 1.5.0. Support for the week and ordinal formats was added in version 2.3.0.
If a string does not match any of the above formats and is not able to be parsed with Date.parse, moment#isValid will return false.
moment("not a real date").isValid();
moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);
If you know the format of an input string, you can use that to parse a moment.
moment("12-25-1995", "MM-DD-YYYY");
The parser ignores non-alphanumeric characters, so both of the following will return the same thing.
moment("12-25-1995", "MM-DD-YYYY");
moment("12/25/1995", "MM-DD-YYYY");
The parsing tokens are similar to the formatting tokens used in moment#format.
Year, month, and day tokens
Description
4 or 2 digit year
2 digit year
Quarter of year. Sets month to first month in quarter.
Month number
Jan..December
Month name in locale set by moment.locale()
Day of month
Day of month with ordinal
Day of year
Unix timestamp
Unix ms timestamp
YYYY from version 2.10.5 supports 2 digit years, and converts them to a year
near 2000 (same as 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
start days.
Description
Locale 4 digit week year
Locale 2 digit week year
Locale week of year
Locale day of week
Mon...Sunday
Day name in locale set by moment.locale()
ISO 4 digit week year
ISO 2 digit week year
ISO week of year
ISO day of week
Hour, minute, second, millisecond, and offset tokens
Description
24 hour time
12 hour time used with a A.
Post or ante meridiem
Tenths of a second
Hundreds of a second
Thousandths of a second
fractional seconds
Offset from UTC as +-HH:mm, +-HHmm, or Z
From version 2.10.5: fractional second tokens length 4 up to 9 can parse
any number of digits, but will only consider the top 3 (milliseconds). Use if
you have the time printed with many fractional digits and want to consume the
Locale aware date and time formats are also available using LT LTS L LL LLL
LLLL. They were added in version 2.2.1, except LTS which was added
Z ZZ were added in version 1.2.0.
S SS SSS were added in version 1.6.0.
X was added in version 2.0.0.
Unless you specify a timezone offset, parsing a string will create a date in the current timezone.
moment(" 4:30",
"YYYY-MM-DD HH:mm");
moment(" 4:30 +0000", "YYYY-MM-DD HH:mm Z");
If the moment that results from the parsed input does not exist, moment#isValid will return false.
moment("2010 13",
"YYYY MM").isValid();
moment("",
"YYYY MM DD").isValid();
moment("",
"YYYY MM DD").isValid();
moment("2010 notamonth 29", "YYYY MMM DD").isValid();
As of version 2.0.0, a locale key can be passed as the third parameter to moment() and moment.utc().
moment('2012 juillet', 'YYYY MMM', 'fr');
moment('2012 July',
'YYYY MMM', 'en');
Moment's parser is very forgiving, and this can lead to undesired behavior. As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly.
moment('It is ', 'YYYY-MM-DD').isValid();
moment('It is ', 'YYYY-MM-DD', true).isValid();
moment('',
'YYYY-MM-DD', true).isValid();
You can use both locale and strictness.
moment('', 'YYYY-MM-DD', 'fr', true);
Parsing two digit years
By default, two digit years above 68 are assumed to be in the 1900's and years 68 or below are assumed to be in the 2000's. This can be changed by replacing the moment.parseTwoDigitYear method.
moment(String, String[], String, Boolean);
If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.
This is the same as , only it will try to match the input to multiple formats.
moment("12-25-1995", ["MM-DD-YYYY", "YYYY-MM-DD"]);
Starting in version 2.3.0, Moment uses some simple heuristics to determine which format to use. In order:
Prefer formats resulting in
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"]);
moment("05-06-1995", ["MM-DD-YYYY", "DD-MM-YYYY"]);
You may also specify a locale and strictness argument. They work the same was as they do in the single format case.
moment("29-06-1995", ["MM-DD-YYYY", "DD-MM-YYYY"], 'fr');
moment("29-06-1995", ["MM-DD-YYYY", "DD-MM-YYYY"], true);
moment("05-06-1995", ["MM-DD-YYYY", "DD-MM-YYYY"], 'fr', true);
Note: Parsing multiple formats is considerably slower than parsing a single format. If you can avoid it, it is much faster to parse a single format.
moment(String, moment.CUSTOM_FORMAT, [String], [Boolean]);
moment(String, [..., moment.ISO_8601, ...], [String], [Boolean]);
is a standard for time and duration display. Moment already supports parsing iso-8601 strings, but this can be specified explicitly in the format/list of formats when constructing a moment.
To specify iso-8601 parsing use moment.ISO_8601 constant. More formats will be added in the future.
moment("T05:06:07", moment.ISO_8601);
moment("T05:06:07", ["YYYY", moment.ISO_8601]);
moment({unit: value, ...});
moment({ hour:15, minute:10 });
moment({ y
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});
You can create a moment by specifying some of the units in an object.
Omitted units default to 0 or the current date, month, and year.
day and date key both mean day-of-the-month.
date was added in 2.8.4.
Note that like moment(Array) and new Date(year, month, date), months are 0 indexed.
moment(Number);
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).
var day = moment(6);
moment.unix(Number)
To create a moment from a Unix timestamp (seconds since the Unix Epoch), use moment.unix(Number).
var day = moment.unix();
This is implemented as moment(timestamp * 1000), so partial seconds in the input timestamp are included.
var day = moment.unix(.721);
moment(Date);
You can create a Moment with a pre-existing native Javascript Date object.
var day = new Date(2011, 9, 16);
var dayWrapper = moment(day);
This clones Date further changes to the Date won't affect the Moment, and vice-versa.
moment(Number[]);
You can create a moment with an array of numbers that mirror the parameters passed to
[year, month, day, hour, minute, second, millisecond]
moment([2010, 1, 14, 15, 25, 50, 125]);
Any value past the year is optional, and will default to the lowest possible number.
moment([2010]);
moment([2010, 6]);
moment([2010, 6, 10]);
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[]).
moment.utc([2010, 1, 14, 15, 25, 50, 125]);
Note: Because this mirrors the native Date parameters, months, hours, minutes, seconds, and milliseconds are all zero indexed. Years and days of the month are 1 indexed.
This is often the cause of frustration, especially with months, so take note!
If the date represented by the array does not exist, moment#isValid will return false.
moment([2010, 13]).isValid();
moment([2010, 10, 31]).isValid();
moment([2010, 1, 29]).isValid();
moment(String);
Microsoft Web API returns JSON dates in proper ISO-8601 format by default, but older ASP.NET technologies may return dates in JSON as /Date(6)/ or /Date(6-0700)/
If a string that matches this format is passed in, it will be parsed correctly.
moment("/Date(6-0700)/");
moment(Moment);
All moments are mutable. If you want a clone of a moment, you can do so explicitly or implicitly.
Calling moment() on a moment will clone it.
var a = moment([2012]);
var b = moment(a);
a.year(2000);
Additionally, you can call moment#clone to clone a moment.
var a = moment([2012]);
var b = a.clone();
a.year(2000);
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);
By default, moment parses and displays in local time.
If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment().
This brings us to an interesting feature of Moment.js. UTC mode.
While in UTC mode, all display methods will display in UTC time instead of local time.
moment().format();
moment.utc().format();
Additionally, while in UTC mode, all getters and setters will internally use the Date#getUTC* and Date#setUTC* methods instead of the Date#get* and Date#set* methods.
moment.utc().seconds(30) === new Date().setUTCSeconds(30);
moment.utc().seconds()
=== new Date().getUTCSeconds();
It is important to note that though the displays differ above, they are both the same moment in time.
var a = moment();
var b = moment.utc();
a.format();
b.format();
a.valueOf();
b.valueOf();
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
var a = moment.utc([2011, 0, 1, 8]);
a.hours();
a.local();
a.hours();
moment.parseZone(String)
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.parseZone("T00:00:00-13:00").zone();
moment.parseZone is equivalent to parsing the string and using moment#zone to parse the zone.
var s = "T00:00:00-13:00";
moment(s).zone(s);
Note: this method only works for a single string argument, not a string and format.
moment().isValid();
Moment applies stricter initialization rules than the Date constructor.
new Date(2013, 25, 14).toString();
moment([2015, 25, 35]).format();
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('', []). 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("T10:20:90");
m.isValid();
m.invalidAt();
The return value has the following meaning:
milliseconds
Note: In case of multiple wrong units the first one is returned (because
days validity may depend on month, for example).
moment("15", "hh")
You can create a moment object specifying only some of the units, and the rest
will be defaulted to the current day, month or year, or 0 for hours, minutes,
seconds and milliseconds.
Defaulting to now, when nothing is passed:
Defaulting to today, when only hours, minutes, seconds and milliseconds are passed:
moment(5, &HH&);
// today, 5:00:00.000
moment({hour: 5});
// today, 5:00:00.000
moment({hour: 5, minute: 10});
// today, 5:10.00.000
moment({hour: 5, minute: 10, seconds: 20});
// today, 5:10.20.000
moment({hour: 5, minute: 10, seconds: 20, milliseconds: 300});
// today, 5:10.20.300
Defaulting to this month and year, when only days and smaller units are passed:
moment(5, "DD");
moment("4 05:06:07", "DD hh:mm:ss");
Defaulting to this year, if year is not specified:
moment(3, "MM");
moment("Apr 4 05:06:07", "MMM DD hh:mm:ss");
Moment.js uses overloaded getters and setters. You may be familiar with this pattern from its use in jQuery.
Calling these methods without parameters acts as a getter, and calling them with a parameter acts as a setter.
These map to the corresponding function on the native Date object.
moment().seconds(30) === new Date().setSeconds(30);
moment().seconds()
=== new Date().getSeconds();
If you are in , they will map to the UTC equivalent.
moment.utc().seconds(30) === new Date().setUTCSeconds(30);
moment.utc().seconds()
=== new Date().getUTCSeconds();
For convenience, both singular and plural method names exist as of version 2.0.0.
Note: All of these methods mutate the original moment when used as setters.
moment().millisecond(Number);
moment().millisecond();
moment().milliseconds(Number);
moment().milliseconds();
Gets or sets the milliseconds.
Accepts numbers from 0 to 999. If the range is exceeded, it will bubble up to the seconds.
moment().second(Number);
moment().second();
moment().seconds(Number);
moment().seconds();
Gets or sets the seconds.
Accepts numbers from 0 to 59. If the range is exceeded, it will bubble up to the minutes.
moment().minute(Number);
moment().minute();
moment().minutes(Number);
moment().minutes();
Gets or sets the minutes.
Accepts numbers from 0 to 59. If the range is exceeded, it will bubble up to the hours.
moment().hour(Number);
moment().hour();
moment().hours(Number);
moment().hours();
Gets or sets the hour.
Accepts numbers from 0 to 23. If the range is exceeded, it will bubble up to the day.
moment().date(Number);
moment().date();
moment().dates(Number);
moment().dates();
Gets or sets the day of the month.
Accepts numbers from 1 to 31. If the range is exceeded, it will bubble up to the months.
Note: Moment#date is for the date of the month, and Moment#day is for the day of the week.
moment().day(Number|String);
moment().day();
moment().days(Number|String);
moment().days();
Gets or sets the day of the week.
This method can be used to set the day of the week, with Sunday as 0 and Saturday as 6.
If the range is exceeded, it will bubble up to other weeks.
moment().day(-7);
moment().day(7);
moment().day(10);
moment().day(24);
Note: Moment#date is for the date of the month, and Moment#day is for the day of the week.
As of 2.1.0, a day name is also supported. This is parsed in the moment's current locale.
moment().day("Sunday");
moment().day("Monday");
moment().weekday(Number);
moment().weekday();
Gets or sets the day of the week according to the locale.
If the locale assigns Monday as the first day of the week, moment().weekday(0) will be Monday.
If Sunday is the first day of the week, moment().weekday(0) will be Sunday.
As with moment#day, if the range is exceeded, it will bubble up to other weeks.
moment().weekday(-7);
moment().weekday(7);
moment().weekday(-7);
moment().weekday(7);
moment().isoWeekday(Number);
moment().isoWeekday();
Gets or sets the
with 1 being Monday and 7 being Sunday.
moment().isoWeekday(1);
moment().isoWeekday(7);
moment().dayOfYear(Number);
moment().dayOfYear();
Gets or sets the day of the year.
Accepts numbers from 1 to 366. If the range is exceeded, it will bubble up to the years.
moment().week(Number);
moment().week();
moment().weeks(Number);
moment().weeks();
Gets or sets the week of the year.
Because different locales define week of year numbering differently, Moment.js added moment#week to get/set the localized week of the year.
The week of the year varies depending on which day is the first day of the week (Sunday, Monday, etc), and which week is the first week of the year.
For example, in the United States, Sunday is the first day of the week. The week with January 1st in it is the first week of the year.
In France, Monday is the first day of the week, and the week with January 4th is the first week of the year.
The output of moment#week will depend on the
for that moment.
When setting the week of the year, the day of the week is retained.
moment().isoWeek(Number);
moment().isoWeek();
moment().isoWeeks(Number);
moment().isoWeeks();
Gets or sets the .
When setting the week of the year, the day of the week is retained.
moment().month(Number|String);
moment().month();
moment().months(Number|String);
moment().months();
Gets or sets the month.
Accepts numbers from 0 to 11. If the range is exceeded, it will bubble up to the year.
Note: Months are zero indexed, so January is month 0.
As of 2.1.0, a month name is also supported. This is parsed in the moment's current locale.
moment().month("January");
moment().month("Feb");
Before version 2.1.0, if a moment changed months and the new month did not have enough days to keep the current day of month, it would overflow to the next month.
As of version 2.1.0, this was changed to be clamped to the end of the target month.
moment([2012, 0, 31]).month(1).format("YYYY-MM-DD");
moment([2012, 0, 31]).month(1).format("YYYY-MM-DD");
moment().quarter();
moment().quarter(Number);
Gets the quarter (1 to 4).
moment('T00:00:00.000').quarter()
moment('T00:00:00.000').subtract(1, 'ms').quarter()
moment('T00:00:00.000').quarter()
moment('T00:00:00.000').subtract(1, 'ms').quarter()
moment('T00:00:00.000').quarter()
moment('T00:00:00.000').subtract(1, 'ms').quarter()
moment('T00:00:00.000').quarter()
moment('T00:00:00.000').subtract(1, 'ms').quarter()
Sets the quarter (1 to 4).
moment('T00:00:00.000').quarter(2)
moment('T05:06:07.000').quarter(2).format()
moment().year(Number);
moment().year();
moment().years(Number);
moment().years();
Gets or sets the year.
Accepts numbers from -270,000 to 270,000.
moment().weekYear(Number);
moment().weekYear();
Gets or sets the week-year according to the locale.
Because the first day of the first week does not always fall on the first day of the year, sometimes the week-year will differ from the month year.
For example, in the US, the week that contains Jan 1 is always the first week. In the US, weeks also start on Sunday. If Jan 1 was a Monday, Dec 31 would belong to the same week as Jan 1, and thus the same week-year as Jan 1. Dec 30 would have a different week-year than Dec 31.
moment().isoWeekYear(Number);
moment().isoWeekYear();
Gets or sets the .
moment().weeksInYear();
Gets the number of weeks according to locale in the current moment's year.
moment().isoWeeksInYear();
Gets the number of weeks in the current moment's year, according to .
moment().get('year');
moment().get('month');
moment().get('date');
moment().get('hour');
moment().get('minute');
moment().get('second');
moment().get('millisecond');
String getter. In general
moment().get(unit) === moment()[unit]()
Units are case insensitive, and support plural and short forms: year (years,
y), month (months, M), date (dates, D), hour (hours, h), minute (minutes, m),
second (seconds, s), millisecond (milliseconds, ms).
moment().set(String, Int);
moment().set(Object(String, Int));
Generic setter, accepting unit as first argument, and value as second:
moment().set('year', 2013);
moment().set('month', 3);
moment().set('date', 1);
moment().set('hour', 13);
moment().set('minute', 20);
moment().set('second', 30);
moment().set('millisecond', 123);
moment().set({'year': 2013, 'month': 3});
Units are case insensitive, and support plural and short forms: year (years,
y), month (months, M), date (dates, D), hour (hours, h), minute (minutes, m),
second (seconds, s), millisecond (milliseconds, ms).
Object parsing was added in 2.9.0
moment.max(Moment[,Moment...]);
Returns the maximum (most distant future) of the given moment instances.
For example:
var a = moment().subtract(1, 'day');
var b = moment().add(1, 'day');
moment.max(a, b);
With no arguments the function returns a moment instance with the current time.
From version 2.10.5, if an invalid moment is one of the arguments, the result
is an invalid moment.
moment.max(moment(), moment.invalid()).isValid() === false
moment.max(moment.invalid(), moment()).isValid() === false
moment.min(Moment[,Moment...]);
Returns the minimum (most distant past) of the given moment instances.
For example:
var a = moment().subtract(1, 'day');
var b = moment().add(1, 'day');
moment.min(a, b);
With no arguments the function returns a moment instance with the current time.
From version 2.10.5, if an invalid moment is one of the arguments, the result
is an invalid moment.
moment.min(moment(), moment.invalid()).isValid() === false
moment.min(moment.invalid(), moment()).isValid() === false
Once you have a Moment, you may want to manipulate it in some way. There are a number of methods to help with this.
Moment.js uses the , also known as . This allows you to do crazy things like the following.
moment().add(7, 'days').subtract(1, 'months').year(2009).hours(0).minutes(0).seconds(0);
Note: It should be noted that moments are mutable. Calling any of the manipulation methods will change the original moment.
If you want to create a copy and manipulate it, you should use moment#clone before manipulating the moment.
moment().add(Number, String);
moment().add(Duration);
moment().add(Object);
Mutates the original moment by adding time.
This is a pretty robust function for adding time to an existing moment. To add time, pass the key of what time you want to add, and the amount you want to add.
moment().add(7, 'days');
There are some shorthand keys as well if you're into that whole brevity thing.
moment().add(7, 'd');
milliseconds
If you want to add multiple different keys at the same time, you can pass them in as an object literal.
moment().add(7, 'days').add(1, 'months');
moment().add({days:7,months:1});
There are no upper limits for the amounts, so you can overload any of the parameters.
moment().add(1000000, 'milliseconds');
moment().add(360, 'days');
If the day of the month on the original date is greater than the number of days in the final month,
the day of the month will change to the last day in the final month.
moment([2010, 0, 31]);
moment([2010, 0, 31]).add(1, 'months');
There are also special considerations to keep in mind when adding time that crosses over daylight saving time.
If you are adding years, months, weeks, or days, the original hour will always match the added hour.
var m = moment(new Date(2011, 2, 12, 5, 0, 0));
m.hours();
m.add(1, 'days').hours();
If you are adding hours, minutes, seconds, or milliseconds, the assumption is that you want precision to the hour, and will result in a different hour.
var m = moment(new Date(2011, 2, 12, 5, 0, 0));
m.hours();
m.add(24, 'hours').hours();
Alternatively, you can use
to add to moments.
var duration = moment.duration({'days' : 1});
moment([2012, 0, 31]).add(duration);
Before version 2.8.0, the moment#add(String, Number) syntax was also supported. It has been deprecated in favor of moment#add(Number, String).
moment().add('seconds', 1);
moment().add(1, 'seconds');
moment().subtract(Number, String);
moment().subtract(Duration);
moment().subtract(Object);
Mutates the original moment by subtracting time.
This is exactly the same as moment#add, only instead of adding time, it subtracts time.
moment().subtract(7, 'days');
Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).
moment().subtract('seconds', 1);
moment().subtract(1, 'seconds');
moment().startOf(String);
Mutates the original moment by setting it to the start of a unit of time.
moment().startOf('year');
moment().startOf('month');
moment().startOf('quarter');
moment().startOf('week');
moment().startOf('isoWeek');
moment().startOf('day');
moment().startOf('hour');
moment().startOf('minute');
moment().startOf('second');
These shortcuts are essentially the same as the following.
moment().startOf('year');
moment().month(0).date(1).hours(0).minutes(0).seconds(0).milliseconds(0);
moment().startOf('hour');
moment().minutes(0).seconds(0).milliseconds(0)
As of version 2.0.0, moment#startOf('day') replaced moment#sod.
Note: moment#startOf('week') was added in version 2.0.0.
As of version 2.1.0, moment#startOf('week') uses the locale aware week start day.
Note: moment#startOf('isoWeek') was added in version 2.2.0.
moment().endOf(String);
Mutates the original moment by setting it to the end of a unit of time.
This is the same as moment#startOf, only instead of setting to the start of a unit of time, it sets to the end of a unit of time.
moment().endOf("year");
As of version 2.0.0, moment#endOf('day') replaced moment#eod.
Note: moment#endOf('week') was added in version 2.0.0.
As of version 2.1.0, moment#endOf('week') uses the locale aware week start day.
From 2.1.0, Deprecated 2.7.0
moment().max(Moment|String|Number|Date|Array);
NOTE: This function has been deprecated in 2.7.0. Consider
Limits the moment to a maximum of another moment value. So a.max(b) is the same as a = moment.min(a, b) (note that max is converted to min).
Sometimes, server clocks are not quite in sync with client clocks. This ends up displaying humanized strings such as &in a few seconds& rather than &a few seconds ago&. You can prevent that with moment#max():
This is the counterpart for moment#min.
var momentFromServer = moment(input);
var clampedMoment = momentFromServer.max();
You can pass anything to moment#max that you would pass to moment().
moment().max(moment().add(1, 'd'));
moment().max("T20:00:00+0800");
moment().max("Jan 1 2001", "MMM D YYYY");
moment().max(new Date(2012, 1, 8));
From 2.1.0, Deprecated 2.7.0
moment().min(Moment|String|Number|Date|Array);
NOTE: This function has been deprecated in 2.7.0. Consider
Limits the moment to a minimum of another moment value. So a.min(b) is the same as a = moment.max(a, b) (note that min is converted to max).
This is the counterpart for moment#max.
moment().min("T20:00:00+0800");
This can be used in conjunction with moment#max to clamp a moment to a range.
= moment().startOf('week');
= moment().endOf('week');
var actual = moment().min(start).max(end);
moment().local();
Sets a flag on the original moment to internally use Date#get* and Date#set* instead of Date#getUTC* and Date#setUTC*.
var a = moment.utc([2011, 0, 1, 8]);
a.hours();
a.local();
a.hours();
for more information on UTC mode.
moment().utc();
Sets a flag on the original moment to internally use Date#getUTC* and Date#setUTC* instead of Date#get* and Date#set*.
var a = moment([2011, 0, 1, 8]);
a.hours();
a.hours();
for more information on UTC mode.
moment().utcOffset();
moment().utcOffset(Number|String);
Get the utc offset in minutes.
NOTE: Unlike
function returns the real offset from UTC, not the reverse offset (as returned
by Date.prototype.getTimezoneOffset).
Getting the utcOffset of the current object:
moment().utcOffset();
Setting the utc offset by supplying minutes. Note that once you set an offset,
it's fixed and won't change on its own (i.e there are no DST rules). If you want
an actual timezone -- time in a particular location, like
America/Los_Angeles, consider .
moment().utcOffset(120);
If the input is less than 16 and greater than -16, it will interpret your input as hours instead.
moment().utcOffset(8);
moment().utcOffset(480);
It is also possible to set the utc offset from a string.
moment().utcOffset("+08:00");
moment().utcOffset(8);
moment().utcOffset(480);
moment#utcOffset will search the string for the first match of +00:00 +0000
-00:00 -0000, so you can even pass an ISO8601 formatted string and the moment
will be changed to that utc offset.
Note that the string is required to start with the + or - character.
Passing a string that
does not start with + or - will be interpreted as if it were &+00:00&.
moment().utcOffset("T07:00:00+08:00");
From 1.2.0, deprecated 2.9.0+
moment().zone();
moment().zone(Number|String);
NOTE: This function has been deprecated in 2.9.0. Consider
Get the timezone offset in minutes.
moment().zone();
As of version 2.1.0, it is possible to set the offset by passing in the number of minutes offset from GMT.
moment().zone(120);
If the input is less than 16 and greater than -16, it will interpret your input as hours instead.
moment().zone(480);
moment().zone(8);
It is also possible to set the zone from a string.
moment().zone("-08:00");
moment#zone will search the string for the first match of +00:00 + -0000, so you can even pass an ISO8601 formatted string and the moment will be changed to that zone.
moment().zone("T07:00:00-08:00");
Once parsing and manipulation are done, you need some way to display the moment.
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();
moment().format("dddd, MMMM Do YYYY, h:mm:ss a");
moment().format("ddd, hA");
moment('gibberish').format('YYYY MM DD');
1 2 ... 11 12
1st 2nd ... 11th 12th
01 02 ... 11 12
Jan Feb ... Nov Dec
January February ... November December
Day of Month
1 2 ... 30 31
1st 2nd ... 30th 31st
01 02 ... 30 31
Day of Year
1 2 ... 364 365
1st 2nd ... 364th 365th
001 002 ... 364 365
Day of Week
0 1 ... 5 6
0th 1st ... 5th 6th
Su Mo ... Fr Sa
Sun Mon ... Fri Sat
Sunday Monday ... Friday Saturday
Day of Week (Locale)
0 1 ... 5 6
Day of Week (ISO)
1 2 ... 6 7
Week of Year
1 2 ... 52 53
1st 2nd ... 52nd 53rd
01 02 ... 52 53
Week of Year (ISO)
1 2 ... 52 53
1st 2nd ... 52nd 53rd
01 02 ... 52 53
70 71 ... 29 30
70 71 ... 29 30
Week Year (ISO)
70 71 ... 29 30
0 1 ... 22 23
00 01 ... 22 23
1 2 ... 11 12
01 02 ... 11 12
0 1 ... 58 59
00 01 ... 58 59
0 1 ... 58 59
00 01 ... 58 59
Fractional Second
0 1 ... 8 9
00 01 ... 98 99
000 001 ... 998 999
SSSS ... SSSSSSSSS
000[0..] 001[0..] ... 998[0..] 999[0..]
EST CST ... MST PST
Note: as of 1.6.0, the z/zz format tokens have been deprecated.
-07:00 -06:00 ... +06:00 +07:00
Unix Timestamp
Unix Millisecond Timestamp
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
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 with seconds
8:30:25 PM
Month numeral, day of month, year
09/04/1986
Month name, day of month, year
September 4 1986
Sep 4 1986
Month name, day of month, year, time
September 4
Month name, day of month, day of week, year, time
Thursday, September 4
Thu, Sep 4
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
To escape characters in format strings, you can wrap the characters in square brackets.
moment().format('[today] dddd');
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
Formatting speed
To compare Moment.js formatting speed against other libraries, check out .
Other tokens
If you are more comfortable working with strftime instead of LDML-like parsing tokens, you can use Ben Oakes' plugin. .
Default format
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.
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();
If you pass true, you can get the value without the suffix.
moment([2007, 0, 29]).fromNow();
moment([2007, 0, 29]).fromNow(true);
The base strings are .
The breakdown of which string is displayed for each length of time is outlined in the table below.
Sample Output
0 to 45 seconds
a few seconds ago
45 to 90 seconds
a minute ago
90 seconds to 45 minutes
2 minutes ago ... 45 minutes ago
45 to 90 minutes
an hour ago
90 minutes to 22 hours
2 hours ago ... 22 hours ago
22 to 36 hours
36 hours to 25 days
2 days ago ... 25 days ago
25 to 45 days
a month ago
45 to 345 days
2 months ago ... 11 months ago
345 to 545 days (1.5 years)
a year ago
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.
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]);
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.from([2007, 0, 29]);
a.from(new Date(2007, 0, 29));
a.from("");
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]);
= moment([2007, 0, 10]);
end.from(start);
end.from(start, true);
From version 2.10.3, if any of the endpoints are invalid the result is the
localized Invalid date string.
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 , but gives
the opposite interval: a.fromNow() = - a.toNow().
This is similar 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();
If you pass true, you can get the value without the prefix.
moment([2007, 0, 29]).toNow();
moment([2007, 0, 29]).toNow(true);
The base strings are .
The breakdown of which string is displayed for each length of time is outlined in the table below.
Sample Output
0 to 45 seconds
in seconds
45 to 90 seconds
in a minute
90 seconds to 45 minutes
in 2 minutes ... in 45 minutes
45 to 90 minutes
in an hour
90 minutes to 22 hours
in 2 hours ... in 22 hours
22 to 36 hours
36 hours to 25 days
in 2 days ... in 25 days
25 to 45 days
in a month
45 to 345 days
in 2 months ... in 11 months
345 to 547 days (1.5 years)
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.
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]);
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([2007, 0, 29]);
a.to(new Date(2007, 0, 29));
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]);
= moment([2007, 0, 10]);
end.to(start);
end.to(start, true);
From version 2.10.3, if any of the endpoints are invalid the result is the
localized Invalid date string.
moment().calendar();
moment().calendar(referenceTime);
moment().calendar(referenceTime, formats);
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.
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
These strings are localized, and .
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 referenceTime
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]);
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')
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.
var a = moment([2008, 6]);
var b = moment([2007, 0]);
a.diff(b, 'years');
a.diff(b, 'years', true);
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 easy way to think of this is by replacing .diff( with a minus operator.
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.
moment().valueOf();
+moment();
moment#valueOf simply outputs the number of milliseconds since the Unix Epoch, just like Date#valueOf.
moment(6).valueOf();
+moment(6);
To get a Unix timestamp (the number of seconds since the epoch) from a Moment, use moment#unix.
moment().unix();
moment#unix outputs a Unix timestamp (the number of seconds since the Unix Epoch).
moment(6).unix();
This value is floored to the nearest second, and does not include a milliseconds component.
moment().daysInMonth();
Get the number of days in the current month.
moment("2012-02", "YYYY-MM").daysInMonth()
moment("2012-01", "YYYY-MM").daysInMonth()
moment().toDate();
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#native has been replaced by moment#toDate and has been deprecated as of 1.6.0.
moment().toArray();
This returns an array that mirrors the parameters from new Date().
moment().toArray();
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()
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()
moment().toISOString();
Formats a string to the ISO8601 standard.
moment().toISOString()
From version 2.8.4 the native Date.prototype.toISOString is used if
available, for performance reasons.
moment().toObject();
This returns an object containing year, month, day-of-month, hour, minute,
seconds, milliseconds.
moment().toObject()
moment().isBefore(Moment|String|Number|Date|Array);
moment().isBefore(Moment|String|Number|Date|Array, String);
Check if a moment is before another moment.
moment('').isBefore('');
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('').isBefore('', 'year');
moment('').isBefore('', 'year');
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 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
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.
moment('').isSame('');
If you want to limit the granularity to a unit other than milliseconds, pass it as the second parameter.
moment('').isSame('', 'year');
moment('').isSame('', 'year');
moment('').isSame('', 'year');
moment('').isSame('', 'year');
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('').isSame('', 'month');
moment('').isSame('', 'day');
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 day hour minute second
moment().isAfter(Moment|String|Number|Date|Array);
moment().isAfter(Moment|String|Number|Date|Array, String);
Check if a moment is after another moment.
moment('').isAfter('');
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('').isAfter('', 'year');
moment('').isAfter('', 'year');
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 day hour minute second
If nothing is passed to moment#isAfter, it will default to the current time.
moment().isAfter();
moment().isBetween(moment-like, moment-like);
moment().isBetween(moment-like, moment-like, String);
Check if a moment is between two other moments, optionally looking at unit
scale (minutes, hours, days, etc).
The match is exclusive.
moment('').isBetween('', '');
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
moment('').isBetween('', '', 'year');
moment('').isBetween('', '', 'year');
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, day, hour, minute, and second.
moment().isLeapYear();
moment#isLeapYear returns true if that year is a leap year, and false if it is not.
moment([2000]).isLeapYear()
moment([2001]).isLeapYear()
moment([2100]).isLeapYear()
moment().isDST();
moment#isDST checks if the current moment is in daylight saving time.
moment([2011, 2, 12]).isDST();
moment([2011, 2, 14]).isDST();
moment(' 2:30', 'YYYY-MM-DD HH:mm').isDSTShifted()
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(' 2:30', 'YYYY-MM-DD HH:mm').format();
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.
moment.isMoment(obj);
To check if a variable is a moment object, use moment.isMoment().
moment.isMoment()
moment.isMoment(new Date())
moment.isMoment(moment())
moment.isDate(obj);
To check if a variable is a native js Date object, use moment.isDate().
moment.isDate();
moment.isDate(new Date());
moment.isDate(moment());
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.locale(String);
moment.locale(String[]);
moment.locale(String, Object);
moment.lang(String);
moment.lang(String[]);
moment.lang(String, Object);
By default, Moment.js comes with English 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
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("_"),
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("_"),
longDateFormat : {
LT : "HH:mm",
LTS : "HH:mm:ss",
L : "DD/MM/YYYY",
LL : "D MMMM YYYY",
LLL : "D MMMM YYYY LT",
LLLL : "dddd D MMMM YYYY LT"
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 : "une année",
yy : "%d années"
ordinalParse : /\d{1,2}(er|ème)/,
ordinal : function (number) {
return number + (number === 1 ? 'er' : 'ème');
meridiemParse: /PD|MD/,
isPM: function (input) {
return input.charAt(0) === 'M';
meridiem : function (hours, minutes, isLower) {
return hours & 12 ? 'PD' : 'MD';
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(9).fromNow()
moment.locale('en');
moment(9).fromNow()
As of 2.8.0, changing the global locale doesn't affect existing instances.
moment.locale('fr');
var m = moment(9);
m.fromNow();
moment.locale('en');
m.fromNow();
moment(9).fromNow();
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');
moment.locale('tq');
You may also specify a list of locales, and Moment will use the first one it has localizations for.
moment.locale(['tq', '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');
Finally, Moment will search intelligently through an array of locales and their substrings.
moment.locale('en-NZ', 'en-AU');
moment().locale(String);
moment().lang(String);
A global locale configuration can be problematic when passing around moments that may need to be formatted into different locale.
In 1.7.0 we added instance specific locale configurations.
moment.locale('en');
var localLocale = moment();
localLocale.locale('fr');
localLocale.format('LLLL');
moment().format('LLLL');
moment.locale('es');
localLocale.format('LLLL');
moment().format('LLLL');
localLocale.locale(false);
localLocale.format('LLLL');
moment().format('LLLL');
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]))
fr.locale('en');
fr.localeData().months(moment([2012, 0]))
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 was it does in the .
moment.locale(String);
Loading locales in NodeJS is super easy. If there is a locale file in moment-root/locale/ named after that key, the first call to moment.locale will load it.
var moment = require('moment');
moment.locale('fr');
moment(9).fromNow();
If you want your locale supported, create a pull request to the develop branch with the .
moment.locale(String, Object);
moment.lang(String, Object);
Loading locales in the browser just requires you to include the locale files.
&script src=&moment.js&&&/script&
&script src=&locale/fr.js&&&/script&
&script src=&locale/pt.js&&&/script&
moment.locale('fr');
// Set the default/global locale
There are minified versions of all locales together:
&script src=&moment.js&&&/script&
&script src=&min/locales.js&&&/script&
To minimize http requests, use our Grunt task to compile
with a custom list of locales:
grunt transpile:fr,it
&script src=&min/moment-with-locales.custom.js&&&/script&
Note: Locale files are defined in
style, so they should work seamlessly in all environments.
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/locale/fr.js and moment/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!
moment.locale();
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');
moment.locale();
moment.locale('fr');
moment.locale();
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',
'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);
Note: Currently, 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();
moment.monthsShort('-MMM-');
And finally, you can combine both the format option and the integer option.
moment.monthsShort('-MMM-', 3);
localeData = moment.localeData()
localeData.months()
localeData.monthsShort()
localeData.monthsParse()
localeData.weekdays()
localeData.weekdaysShort()
localeData.weekdaysMin()
localeData.weekdaysParse()
localeData.longDateFormat()
localeData.isPM()
localeData.meridiem()
localeData.calendar()
localeData.relativeTime()
localeData.pastFuture()
localeData.ordinal()
localeData.preparse()
localeData.postformat()
localeData.weeks()
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:
var currentLocaleData = moment.localeData();
var frLocaleData = moment.localeData('fr');
The returned object has the following methods:
localeData.months(aMoment);
localeData.monthsShort(aMoment);
localeData.monthsParse(longOrShortMonthString);
localeData.weekdays(aMoment);
localeData.weekdaysShort(aMoment);
localeData.weekdaysMin(aMoment);
localeData.weekdaysParse(minShortOrLongWeekdayString);
localeData.longDateFormat(dateFormat);
localeData.isPM(amPmString);
localeData.meridiem(hours, minutes, isLower);
localeData.calendar(key, aMoment);
localeData.relativeTime(number, withoutSuffix, key, isFuture);
localeData.pastFuture(diff, relTime);
localeData.ordinal(number);
localeData.preparse(str);
localeData.postformat(str);
localeData.week(aMoment);
localeData.invalidDate();
localeData.firstDayOfWeek();
localeData.firstDayOfYear();
Moment.js is very easy to customize. In general, you should create a locale setting with your customizations.
moment.locale('en-my-settings', {
However, you can also overwrite an existing locale that has been loaded as well.
moment.locale('en', {
Any settings that are not defined are inherited from the default english settings.
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');
moment.locale('en');
moment.locale('fr', null);
moment.locale('fr');
moment.locale('en', {
months : String[]
moment.locale('en', {
months : Function
moment.lang('en', {
months : String[]
moment.lang('en', {
months : Function
Locale#months should be an array of the month names.
moment.locale('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.locale('en', {
months : function (momentToFormat, format) {
if (/^MMMM/.test(format)) {
return nominative[momentToFormat.month()];
return subjective[momentToFormat.month()];
moment.locale('en', {
monthsShort : String[]
moment.locale('en', {
monthsShort : Function
moment.lang('en', {
monthsShort : String[]
moment.lang('en', {
monthsShort : Function
Locale#monthsShort should be an array of the month abbreviations.
moment.locale('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.locale('en', {
monthsShort : function (momentToFormat, format) {
if (/^MMMM/.test(format)) {
return nominative[momentToFormat.month()];
return subjective[momentToFormat.month()];
moment.locale('en', {
weekdays : String[]
moment.locale('en', {
weekdays : Function
moment.lang('en', {
weekdays : String[]
moment.lang('en', {
weekdays : Function
Locale#weekdays should be an array of the weekdays names.
moment.locale('en', {
weekdays : [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
Locale#weekdays can be a callback function as well.
moment.locale('en', {
weekdays : function (momentToFormat, format) {
return weekdays[momentToFormat.day()];
moment.locale('en', {
weekdaysShort : String[]
moment.locale('en', {
weekdaysShort : Function
moment.lang('en', {
weekdaysShort : String[]
moment.lang('en', {
weekdaysShort : Function
Locale#weekdaysShort should be an array of the weekdays abbreviations.
moment.locale('en', {
weekdaysShort : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
Locale#weekdaysShort can be a callback function as well.
moment.locale('en', {
weekdaysShort : function (momentToFormat, format) {
return weekdaysShort[momentToFormat.day()];
moment.locale('en', {
weekdaysMin : String[]
moment.locale('en', {
weekdaysMin : Function
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.locale('en', {
weekdaysMin : ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
Locale#weekdaysMin can be a callback function as well.
moment.locale('en', {
weekdaysMin : function (momentToFormat, format) {
return weekdaysMin[momentToFormat.day()];
moment.locale('en', {
longDateFormat : Object
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.locale('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.locale('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"
moment.locale('en', {
relativeTime : Object
moment.lang('en', {
relativeTime : Object
Locale#relativeTime should be an object of the replacement strings for moment#from.
moment.locale('en', {
relativeTime : {
future: "in %s",
"seconds",
"a minute",
mm: "%d minutes",
"an hour",
hh: "%d hours",
dd: "%d days",
"a month",
MM: "%d months",
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) {
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. The isFuture argument was added in version 1.6.0.
moment.locale('en', {
meridiem : Function
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.locale('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 "下午";
return "晚上";
Before version 1.6.0, Locale#meridiem was a map of upper and lowercase versions of am/pm.
moment.locale('en', {
meridiem : {
am : 'am',
AM : 'AM',
pm : 'pm',
This has been deprecated. The 1.6.0 callback function syntax is now used instead.
moment.locale('en', {
meridiemParse : RegExp
isPM : Function
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.locale('en', {
isPM : function (input) {
return ((input + '').toLowerCase()[0] === 'p');
To configure what strings should be parsed as input, set the meridiemParse property.
moment.locale('en', {
meridiemParse : /[ap]\.?m?\.?/i
moment.locale('en', {
calendar : Object
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. It should return a formatting string.
function () {
return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
moment.locale('en', {
ordinal : Function
moment.lang('en', {
ordinal : Function
Locale#ordinal should be a function that returns the ordinal for }

我要回帖

更多关于 黄小琥是男是女 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信