Moment.js 文档

Moment.js 已成功用于数百万个项目,我们很高兴为让网络上的日期和时间变得更好做出贡献。截至 2020 年 9 月,Moment 每周的下载量超过 1200 万次!然而,Moment 是为 JavaScript 生态系统的前一个时代而构建的。如今,现代网络看起来大不相同。多年来,Moment 有所发展,但它的设计与 2011 年创建时的设计基本相同。考虑到有多少项目依赖它,我们选择将稳定性优先于新功能。

Moment.js has been successfully used in millions of projects, and we are happy to have contributed to making date and time better on the web. As of September 2020, Moment gets over 12 million downloads per week! However, Moment was built for the previous era of the JavaScript ecosystem. The modern web looks much different these days. Moment has evolved somewhat over the years, but it has essentially the same design as it did when it was created in 2011. Given how many projects depend on it, we choose to prioritize stability over new features.

例如,考虑 Moment 对象是可变的。这是有关 Moment 的常见投诉来源。我们 在我们的使用指南中 解决了这个问题,但它仍然让大多数新用户感到惊讶。将 Moment 更改为不可变对于使用它的每个项目来说都是一个重大变化。创建一个不可变的 "Moment v3" 将是一项艰巨的任务,并且会使 Moment 成为一个完全不同的库。由于这已经在其他库中完成,我们认为保留可变 API 更为重要。

As an example, consider that Moment objects are mutable. This is a common source of complaints about Moment. We address it in our usage guidance but it still comes as a surprise to most new users. Changing Moment to be immutable would be a breaking change for every one of the projects that use it. Creating a "Moment v3" that was immutable would be a tremendous undertaking and would make Moment a different library entirely. Since this has already been accomplished in other libraries, we feel that it is more important to retain the mutable API.

在现代应用中反对使用 Moment 的另一个常见参数是它的大小。Moment 不适用于现代 "摇树优化" 算法,因此它往往会增加 Web 应用包的大小。如果需要国际化或时区支持,Moment 会变得很大。现代网络浏览器(和 Node.js)通过编码为 ECMA-402Intl 对象公开国际化和时区支持。像 Luxon(和其他)这样的库利用了这一点,减少或消除了传送你自己的数据文件的需要。

Another common argument against using Moment in modern applications is its size. Moment doesn't work well with modern "tree shaking" algorithms, so it tends to increase the size of web application bundles. If one needs internationalization or time zone support, Moment can get quite large. Modern web browsers (and Node.js) expose internationalization and time zone support via the Intl object, codified as ECMA-402. Libraries like Luxon (and others) take advantage of this, reducing or removing the need to ship your own data files.

最近,Chrome Dev Tools 仅针对尺寸 开始显示更换 Moment 的建议。我们普遍支持这一举措。

Recently, Chrome Dev Tools started showing recommendations for replacing Moment for the size alone. We generally support this move.

你可能还想阅读:

You may also want to read:

Moment 团队对这些问题进行了详细讨论。我们认识到许多现有项目可能会继续使用 Moment,但我们不希望在未来的新项目中使用 Moment。相反,我们希望 推荐替代品 是当今现代应用中使用的绝佳选择。我们还想推广 JavaScript 语言的 Temporal 补充,它正在寻找反馈和贡献者。

The Moment team has discussed these issues at length. We recognize that many existing projects may continue to use Moment, but we would like to discourage Moment from being used in new projects going forward. Instead, we would like to recommend alternatives that are excellent choices for use in modern applications today. We would also like to promote the Temporal addition to the JavaScript language, which is looking for feedback and contributors.

我们现在通常认为 Moment 是处于维护模式的旧项目。它没有死,但确实已经完成了。

We now generally consider Moment to be a legacy project in maintenance mode. It is not dead, but it is indeed done.

实际上,这意味着:

In practice, this means:

  • 我们不会添加新的特性或功能。

    We will not be adding new features or capabilities.

  • 我们不会将 Moment 的 API 更改为不可变的。

    We will not be changing Moment's API to be immutable.

  • 我们不会解决摇树优化或者包体积的问题。

    We will not be addressing tree shaking or bundle size issues.

  • 我们不会进行任何重大更改(没有版本 3)。

    We will not be making any major changes (no version 3).

  • 我们可能会选择不修复错误或行为怪癖,尤其是当它们是长期存在的已知问题时。

    We may choose to not fix bugs or behavioral quirks, especially if they are long-standing known issues.

具体关于 Moment 的国际化语言环境文件:

With specific regard to Moment's internationalization locale files:

  • 我们可能会选择不接受对区域设置字符串或本地化日期格式的更正,特别是如果它们已经成功地针对其当前形式进行了争论。

    We may choose to not accept corrections to locale strings or localized date formats, especially if they have been argued successfully for their present form.

  • 你必须为区域设置更改提出新的令人信服的参数,并提供重要的非轶事证据来支持你的立场。

    You must make a new compelling argument for locale changes with significant, non-anecdotal evidence to support your position.

  • 如果你要求更改的字符串或格式反映在 CLDR 中,那么你必须先在那里提交更改并让其接受。

    If the string or format you are asking to change is reflected in the CLDR, then you must submit a change there first and have it accepted.

然而,由于我们了解到 Moment 在数百万现有项目中得到了很好的应用:

However, since we understand that Moment is well established in millions of existing projects:

  • 我们将解决出现的关键安全问题。

    We will address critical security concerns as they arise.

  • 我们将在 IANA 时区数据库 版本发布后发布 Moment-Timezone 的数据更新。

    We will release data updates for Moment-Timezone following IANA time zone database releases.

继续使用 Moment 的原因

Reasons to keep using Moment

在大多数情况下,你不应该为新项目选择 Moment。但是,出于某些可能的原因,你可能希望继续使用它。

In most cases, you should not choose Moment for new projects. However there are some possible reasons you might want to keep using it.

浏览器支持

Browser support

Moment 在 Internet Explorer 8 及更高版本上运行良好。相比之下,Luxon 仅适用于 IE 10 及更高版本,并且需要 polyfill 才能这样做。你可以在 Luxon 的文档中阅读更多内容。

Moment works well on Internet Explorer 8 and higher. By contrast, Luxon only works on IE 10 and higher and requires a polyfill to do so. You can read more in Luxon's documentation.

其他库也存在与 Safari 相关的问题,尤其是在移动设备上。如果你强烈要求支持旧版浏览器,那么你可能希望坚持使用 Moment 更长时间。

Other libraries have also had issues with Safari, especially on mobile devices. If you have a strong requirement to support older browsers, then you might want to stick with Moment for a bit longer.

但是,Day.js 报告了与 IE8 及更高版本的兼容性,所以你仍然可能希望考虑替代方案。

However, Day.js reports compatibility with IE8 and higher so you still may wish to consider that alternative.

其他库的依赖

Dependency by other libraries

其他几个库,尤其是日期选择器和图形库,将 Moment 作为依赖。如果你正在使用这样的组件并且找不到替代品,那么你已经在你的项目中包含了 Moment。因此,在整个项目中继续使用 Moment 而不是包含另一个日期和时间库可能是有意义的。

Several other libraries, especially date pickers and graphing libraries, take Moment as a dependency. If you are using such a component and cannot find an alternative, then you are already including Moment in your project. Thus, it might make sense to continue using Moment throughout your project rather than including yet another date and time library.

熟悉程度

Familiarity

如果你是 Moment 的长期用户,你可能已经很好地了解它的 API 和限制。如果是这样,并且上述问题不是你关心的问题,那么你当然可以继续使用它。

If you are a long-time user of Moment, you may already understand its API and limitations well. If so, and the aforementioned issues are not a concern for you, then you certainly can continue to use it.

建议

有几个很好的选择可以考虑使用而不是 Moment。

There are several great options to consider using instead of Moment.

选择时,请考虑:

When choosing, consider that:

  • 一些库被分成模块、插件或配套库。

    Some libraries are split into modules, plugins, or companion libraries.

  • 一些库将 ECMAScript Intl API 用于区域设置、时区或两者。

    Some libraries use the ECMAScript Intl API for locales, time zones, or both.

  • 一些库仍然提供他们自己的语言环境和时区文件,如 Moment 和 Moment-Timezone。

    Some libraries still provide their own locale and time zone files like Moment and Moment-Timezone do.

以下是我们推荐的替代方案:

Here are the alternatives we recommend:

Luxon

Luxon 可以被认为是 Moment 的进化。它由 Isaac Cambron 撰写,他是 Moment 的长期贡献者。请阅读 Luxon 文档中的 为什么会存在 Luxon?对于 Moment 用户 页面。

Luxon can be thought of as the evolution of Moment. It is authored by Isaac Cambron, a long-time contributor to Moment. Please read Why does Luxon exist? and the For Moment users pages in the Luxon documentation.

  • 语言环境:Intl 提供

    Locales: Intl provided

  • 时区:Intl 提供

    Time Zones: Intl provided

Day.js

Day.js 旨在成为 Moment.js 的极简替代品,使用类似的 API。它不是直接替代品,但如果你习惯使用 Moment 的 API 并希望快速上手,请考虑使用 Day.js。

Day.js is designed to be a minimalist replacement for Moment.js, using a similar API. It is not a drop-in replacement, but if you are used to using Moment's API and want to get moving quickly, consider using Day.js.

  • 语言环境:可以单独导入的自定义数据文件

    Locales: Custom data files that can be individually imported

  • 时区:Intl 通过插件提供

    Time Zones: Intl provided, via a plugin

date-fns

Date-fns 提供了一系列用于操作 JavaScript Date 对象的函数。有关更多详细信息,请滚动到 date-fns 主页上的 "为什么使用 date-fns?"。

Date-fns offers a series of functions for manipulating JavaScript Date objects. For more details, scroll to "Why date-fns?" on the date-fns home page.

  • 语言环境:可以单独导入的自定义数据文件

    Locales: Custom data files that can be individually imported

  • 时区:Intl 通过单独的配套库提供

    Time Zones: Intl provided, via a separate companion library

js-Joda

js-Joda 是 Java Three-Ten Backport 的 JavaScript 端口,它是 Java SE 8 java.time 包的 JSR-310 实现的基础。如果你熟悉 java.timeJoda-TimeNoda Time,你会发现 js-Joda 具有可比性。

js-Joda is a JavaScript port of Java's Three-Ten Backport, which is the base for JSR-310 implementation of the Java SE 8 java.time package. If you are familiar with java.time, Joda-Time, or Noda Time, you will find js-Joda comparable.

  • 语言环境:通过附加模块自定义数据文件

    Locales: Custom data files via add-on module

  • 时区:通过附加模块自定义数据文件

    Time Zones: Custom data files via add-on module

不用库

No Library

JavaScript 一直有一个 Date 对象,此处 定义了 ECMAScript (ECMA-262) 规范。

JavaScript has always had a Date object, defined ECMAScript (ECMA-262) specification here.

使用 Date 对象时,请注意以下事项:

When using Date objects, be aware of the following:

  • Date 对象在内部表示具有毫秒精度的 Unix 时间戳。它提供与系统本地时区相互转换的功能,但在内部始终为 UTC。与 Moment 对象不同,它不能设置为使用其他时区;它没有 "mode" 的概念。

    The Date object internally represents a Unix timestamp with millisecond precision. It offers functions that will convert to and from the system's local time zone, but it is always UTC internally. Unlike a Moment object, it can not be set to use another time zone; It has no concept of "mode".

  • 使用 Date.parsenew Date(<string>) 在过去一直存在问题并且实现不一致。当前规范 定义解析 ISO 8601 字符串的变体,其中仅日期形式(如 "2020-09-14")被解析为 UTC,而不是 ISO 8601 解析的本地时间。即便如此,并非所有现代实现都正确地实现了这个规范(例如 Safari)。其他类型的字符串也可能有效,但解析它们是特定于实现的,并且可能会有很大差异 - 尤其是对于旧版浏览器。根据实现和字符串中提供的组件,你可能会对结果感到惊讶。由于这些原因,我们同意 MDN 的声明 的观点,强烈建议不要使用 Date 对象解析字符串。

    Using Date.parse, or new Date(<string>) has been problematic and implemented inconsistently in the past. The current specification defines parsing a variation of ISO 8601 strings, where date-only forms (like "2020-09-14") are parsed as UTC, instead of local time as they would be by ISO 8601. Even then, not all modern implementations have implemented this specification correctly (e.g., Safari). Other types of strings may work, but parsing them is implementation specific and can vary significantly - especially with older browsers. Depending on the implementation, and the components provided in the string, you may be surprised with the result. For these reasons, we agree with MDN's statement that parsing strings with the Date object is strongly discouraged.

现代 JavaScript 环境也将实现 ECMA-402 规范,它提供了 Intl 对象,并定义了 Date 对象的 toLocaleStringtoLocaleDateStringtoLocaleTimeString 函数的行为选项。

Modern JavaScript environments will also implement the ECMA-402 specification, which provides the Intl object, and defines behavioral options of the Date object's toLocaleString, toLocaleDateString, and toLocaleTimeString functions.

使用 Intl 对象时,请注意以下事项:

When using the Intl object, be aware of the following:

  • 并非每个环境都会实现完整的规范。特别是,Node.js 环境需要 ICU 提供的国际化支持。有关详细信息,请参阅 Node.js 文档

    Not every environment will implement the full specification. In particular, Node.js environments require internationalization support provided by ICU. See the Node.js documentation for further details.

  • ECMAScript Intl 兼容性表(由 kangax 提供) 可用于确定支持哪些功能,不支持哪些功能。

    The ECMAScript Intl compatibility table (by kangax) can be useful in determining which features are supported and which are not.

  • 大多数较新的环境通过 Intl.DateTimeFormat 构造函数(以及 Date.toLocaleStringDate.toLocaleDateStringDate.toLocaleTimeString)中的 timeZone 选项提供 IANA 时区支持。此选项可用于获取 Date 对象的基于 UTC 的内部时间戳,并获取已转换为命名时区的字符串。但是,它不能用于将 Date 对象转换为不同的时区。

    Most newer environments provide IANA time zone support via the timeZone option in the Intl.DateTimeFormat constructor (and in Date.toLocaleString, Date.toLocaleDateString, and Date.toLocaleTimeString). This option can be used to take the internal UTC-based timestamp of a Date object and get a string that has been converted to a named time zone. However, it can not be used to convert a Date object to a different time zone.

如果 DateIntl 对象满足你的需求并且你充分理解它们的局限性,那么你可以考虑直接使用它们。

If the Date and Intl objects meet your needs and you fully understand their limitations, then you might consider using them directly.

未来

Temporal - JavaScript 语言中更好的日期和时间!

Temporal - Better dates and times in the JavaScript language!

很快有一天,我们希望 JavaScript 中的日期和时间库不再有强烈的需求。相反,我们将能够使用 JavaScript 语言本身的功能。尽管今天 DateIntl 具有一些功能,但我们从经验和数据中知道还有很大的改进空间。

One day soon, we hope there won't be a strong need for date and time libraries in JavaScript at all. Instead, we will be able to use capabilities of the JavaScript language itself. Though some capabilities are here today with Date and Intl, we know from experience and data that there is significant room for improvement.

通过 ECMA TC39 Temporal 提案 正在努力用 JavaScript 语言制作更好的日期和时间 API。它目前处于 TC39 流程 的第 3 阶段。

The effort to make better date and time APIs in the JavaScript language is being done via The ECMA TC39 Temporal Proposal. It is currently at Stage 3 of the TC39 process.

Temporal 将是一个新的全局对象,充当顶层命名空间(如 Math)。它公开了许多不同类型的对象,包括 Temporal.InstantTemporal.ZonedDateTimeTemporal.PlainDateTimeTemporal.PlainDateTemporal.PlainTimeTemporal.TimeZone 和其他几个。Temporal 手册 显示了许多 "秘诀",其中包含如何在不同场景中使用这些对象的示例。

Temporal will be a new global object that acts as a top-level namespace (like Math). It exposes many separate types of objects including Temporal.Instant, Temporal.ZonedDateTime, Temporal.PlainDateTime, Temporal.PlainDate, Temporal.PlainTime, Temporal.TimeZone and several others. The Temporal Cookbook shows many "recipes" with examples of how these objects can be used in different scenarios.

你今天可以通过 非生产环境 polyfill 试用 Temporal。请试一试,但不要在生产环境中使用它!

You can try out Temporal today, via a non-production polyfill. Please give it a try, but don't use it in production (yet)!

请提供反馈,并考虑为这项工作做出贡献 - 特别是如果你有使用 Moment 或其他日期和时间库的经验!

Please provide feedback, and consider contributing to this effort - especially if you have experience using Moment or other date and time libraries!

Moment 旨在同时在浏览器和 Node.js 中工作。

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

所有代码都应该在这两种环境中工作,并且所有单元测试都在这两种环境中运行。

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

目前 ci 系统使用的浏览器有以下几种:Windows XP 上的 Chrome,Windows 7 上的 IE 8、9 和 10,Windows 10 上的 IE 11,Linux 上的最新 Firefox,以及 OSX 10.8 和 10.11 上的最新 Safari。

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

如果你想尝试下面的示例代码,只需打开浏览器的控制台并输入它们。

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

Node.js

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

或者在 ES6 语法中:

Or in ES6 syntax:

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

注意:在 2.4.0 中,全局导出的 moment 对象已被弃用。它将在下一个主要版本中删除。

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

如果你还想包括 Moment Timezone,请参阅带有示例的 用于 Node.js 的单独的 Moment Timezone 文档

If you want to include Moment Timezone as well, see the separate Moment Timezone docs for Node.js with examples.

Bower

bower

bower install --save moment

值得注意的文件是 moment.jslocale/*.jsmin/moment-with-locales.js

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

Require.js

如果你打算将 moment 与 Require.js 结合使用,我们强烈建议你阅读 此处。还可以升级到 2.14.0 或更高版本以获得最佳体验。

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

首先,你可能已经通过 bower 或 node_modules 或任何其他将 moment.js 与 locales 目录放在基本文件夹中的工具获得了 moment。那么你应该使用像 adapt-pkg-main 这样的工具,或者手动使用 包配置

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

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

通过以上设置,你可以要求核心具有 momentde 区域设置以及 moment/locale/de

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

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

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

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

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

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

对于更复杂的用例,请阅读 @jrburke 的精彩解释

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

Moment 仍然会创建一个 moment 全局,这对插件和其他第三方代码很有用。如果你想压缩这个全局变量,使用模块配置中的 noGlobal 选项。

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

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

如果你未指定 noGlobal,则全局导出的 moment 将打印弃用警告。从下一个主要版本开始,如果你想要这种行为,你必须自己导出它。

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.

对于 2.5.x 版本,如果你使用依赖 Moment 但不兼容 AMD 的其他插件,你可能需要将 wrapShim: true 添加到你的 r.js 配置中。

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

注意:为了允许在 requirejs 环境中加载 moment.js 插件,moment 被创建为命名模块。正因为如此,moment 必须完全按照 "moment" 加载,使用 paths 来确定目录。要求像 "vendor\moment" 这样的路径的 moment 将返回 undefined

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.

注意:从版本 2.9.0 开始,moment 将自身导出为匿名模块,因此,如果你仅使用核心(无语言环境/插件),那么如果将其放在非标准位置,则不需要配置。

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

Browserify

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

注意:存在阻止加载 moment.locale 的错误。

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

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

使用下面的解决方法

Use the workaround below

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

为了包括所有语言环境

In order to include all the locales

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

Webpack

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

注意:默认情况下,webpack 打包所有 Moment.js 语言环境(在 Moment.js 2.18.1 中,这是 160 缩小的 KB)。要去除不必要的语言环境并仅打包使用过的语言环境,请添加 moment-locales-webpack-plugin

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

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

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

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

还有其他资源可以使用 webpack 例如这个 优化 Moment.js。

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

Typescript 2.13.0+

从版本 2.13.0 开始,Moment 包含一个 TypeScript 定义文件。

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

通过 NPM 安装

Install via NPM

npm install moment

在你的 Typescript 文件中导入和使用

Import and use in your Typescript file

const moment = require('moment');

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

注意:如果你在导入 moment 时遇到问题

Note: If you have trouble importing moment

对于 Typescript 2.x,请尝试在 tsconfig.json 文件中的 compilerOptions 中添加 "moduleResolution": "node"

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

对于 Typescript 1.x,请尝试在 tsconfig.json 文件中的 compilerOptions 中添加 "allowSyntheticDefaultImports": true,然后使用以下语法

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

import moment from 'moment';

语言环境导入

Locale Import

要使用 moment.locale,你首先需要导入你的目标语言。

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

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

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

System.js

要加载 moment,请将其放置在 baseURL 配置中 System.config 指定的路径中。然后将其导入你的页面。

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

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

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

如果你需要将 moment 加载为全局,你可以使用元配置来做到这一点:

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

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

或者,要将 Moment 作为全局提供给特定依赖,你可以这样做:

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

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

故障排除

如果你有任何问题,首先要检查的地方是 指南

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

如果你在那里找不到你要找的东西,请尝试在带有 momentjs 标签的 Stack Overflow 上提问。

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

注意:在 Stack Overflow 上看到的一半以上的问题都可以由 这篇博文 回答。

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

你还可以使用 GitHub 问题跟踪器 查找相关问题或打开新问题。

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

此外,Moment 有一个 Gitter,内部团队经常可用。

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

对于一般故障排除帮助,Stack Overflow 是首选论坛。Moment 的维护者在 Stack Overflow 上非常活跃,其他一些知识渊博的用户也是如此。最快的反应将在那里。

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

Moment.js 没有修改原生的 Date.prototype,而是为 Date 对象创建了一个封装器。要获取此封装器对象,只需使用一种受支持的输入类型调用 moment()

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.

Moment 原型通过 moment.fn 暴露。如果你想添加你自己的函数,那就是你要放的地方。

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

为了便于参考,Moment.prototype 上的任何方法在文档中都将被称为 moment#method。所以 Moment.prototype.format == moment.fn.format == moment#format

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

请阅读:

Please read:

  • moment(...) 是本地模式。不明确的输入(没有偏移量)被假定为本地时间。明确的输入(带偏移量)调整为本地时间。

    moment(...) is local mode. Ambiguous input (without offset) is assumed to be local time. Unambiguous input (with offset) is adjusted to local time.

  • moment.utc(...) 是 utc 模式。模糊输入假定为 UTC。明确的输入调整为 UTC。

    moment.utc(...) is utc mode. Ambiguous input is assumed to be UTC. Unambiguous input is adjusted to UTC.

  • moment.parseZone() 保留传入的输入区。模糊输入假定为 UTC。

    moment.parseZone() keep the input zone passed in. Ambiguous input is assumed to be UTC.

  • 带有 moment-timezone 插件的 moment.tz(...) 可以解析特定时区的输入。

    moment.tz(...) with the moment-timezone plugin can parse input in a specific time zone.

请记住,时区和时区偏移量是两个不同的东西。-08:00 的偏移量并不一定意味着你位于美国太平洋时区。

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

有关其他信息,请参阅解析指南

See the Parsing Guide for additional information.

此刻 1.0.0+

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

要获取当前日期和时间,只需调用不带参数的 moment()

To get the current date and time, just call moment() with no parameters.

var now = moment();

这与调用 moment(new Date()) 基本相同。

This is essentially the same as calling moment(new Date()).

注意:从 2.14.0 版本开始,moment([])moment({}) 也回归了。在 2.14.0 之前,他们曾经默认为今天开始,但这是任意的,所以它被改变了。

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

注意:函数参数不传入时默认为 undefined。Moment 将 moment(undefined) 视为 moment()

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

注意:Moment 是在评估时创建的,因此 moment().diff(moment()) 可能并不总是返回 0。有关详细信息,请参阅 这个 GitHub 问题

Note: Moments are created at evaluation time, so moment().diff(moment()) may not always return 0. See this GitHub issue for more details.

字符串 1.0.0+

moment(String);

从字符串创建 moment 时,我们首先检查字符串是否与已知的 ISO 8601 格式匹配,然后检查字符串是否与 RFC 2822 日期时间 格式匹配,如果未找到已知格式,则返回 new Date(string) 格式。

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

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

提醒:浏览器支持解析字符串 不一致。因为没有关于应支持哪些格式的规范,所以在某些浏览器中有效的内容在其他浏览器中无效。

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

为了在解析 ISO 8601 字符串以外的任何内容时获得一致的结果,你应该使用 字符串 + 格式

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

支持的 ISO 8601 字符串

Supported ISO 8601 strings

ISO 8601 字符串需要日期部分。

An ISO 8601 string requires a date part.

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

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

还可以包含时间部分,用空格或大写字母 T 与日期部分分隔。

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

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

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

任何日期部分都可以有时间部分。

Any of the date parts can have a time part.

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

如果包含时间部分,则还可以包含与 UTC 的偏移量,如 +-HH:mm+-HHmm+-HHZ

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

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

注意:2.3.0 版本中添加了对周和序数格式的支持。

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

如果字符串不匹配上述任何一种格式并且无法用 Date.parse 解析,moment#isValid 将返回 false。

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

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

RFC 2822 日期时间格式

The RFC 2822 date time format

在解析 RFC 2822 日期时间之前,会清理字符串以删除任何注释和/或换行符。额外的字符在格式上是合法的,但对创建有效 moment 实例没有任何帮助。

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

清理后,字符串在以下以空格分隔的部分中进行验证,全部使用英语:

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

6 Mar 17 21:22 UT
6 Mar 17 21:22:23 UT
6 Mar 2017 21:22:23 GMT
06 Mar 2017 21:22:23 Z
Mon 06 Mar 2017 21:22:23 z
Mon, 06 Mar 2017 21:22:23 +0000
  1. 三个字母表示的星期几,后跟一个可选的逗号。(可选)

    Day of Week in three letters, followed by an optional comma. (optional)

  2. 日期(1 位或 2 位数字),后跟三个字母的月份和 2 位或 4 位数字的年份

    Day of Month (1 or 2 digit), followed by a three-letter month and 2 or 4 digit year

  3. 以冒号 (:) 分隔的两位数小时和分钟,后跟可选的另一个冒号和两位数的秒

    Two-digit hours and minutes separated by a colon (:), followed optionally by another colon and seconds in 2-digits

  4. 以下格式之一的时区或偏移量:

    Timezone or offset in one of the following formats:

  5. UT : +0000

  6. GMT : +0000

  7. EST | CST | MST | PST | EDT | CDT | MDT | PDT : 美国时区*

    EST | CST | MST | PST | EDT | CDT | MDT | PDT : US time zones*

  8. A - I | K - Z:军事时区*

    A - I | K - Z : Military time zones*

  9. 时间偏移 +/-9999

    Time offset +/-9999

[*] 有关详细信息,请参阅规范的 第 4.3 节

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

解析器还确认星期几(如果包含)与日期一致。

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

字符串 + 格式 1.0.0+

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

如果你知道输入字符串的格式,则可以使用它来解析 moment。

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

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

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

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

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

解析日期和时间时,你可能会得到意想不到的结果。下面的示例可能不会像你预期的那样解析:

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

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

你可以使用严格模式,它将识别解析错误并将 Moment 对象设置为无效:

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

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

解析标记类似于 moment#format 中使用的格式化标记。

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

年、月、日标记

Year, month, and day tokens

令牌区分大小写。

Tokens are case-sensitive.

输入示例描述
YYYY20144 或 2 位数年份。注意:strict 模式只能解析 4 位
YY142 位数年份
Y-25带有任意数字和符号的年份
Q1..4季度。将月份设置为季度的第一个月。
M MM1..12月份
MMM MMMMJan..Decembermoment.locale() 设置的语言环境中的月份名称
D DD1..31一个月中的第几天
Do1st..31st带序号的月份中的第几天
DDD DDDD1..365一年中的某一天
X1410715640.579Unix 时间戳
x1410715640579Unix 毫秒时间戳

YYYY 从 2.10.5 版本开始支持非 strict 模式下的 2 位数年份,并将其转换为接近 2000 年的年份(与 YY 相同)。

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

Y 是在 2.11.1 中添加的。它将匹配任何有符号或无符号的数字。对于不是 4 位数字或纪元之前的年份很有用。它可以用于任何一年。

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

周年、周和星期标记

Week year, week, and weekday tokens

对于这些,小写标记使用区域设置感知周开始日期,大写标记使用 ISO 周日期 开始日期。

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

令牌区分大小写。

Tokens are case-sensitive.

输入示例描述
gggg2014区域设置 4 位数星期年份
gg14区域设置 2 位数周年
w ww1..53一年中的语言环境周
e0..6星期几
ddd ddddMon...Sundaymoment.locale() 设置的语言环境中的日期名称
GGGG2014ISO 4 位数周年
GG14ISO 2 位数周年
W WW1..53一年中的 ISO 周
E1..7ISO 星期几

语言环境感知格式

Locale aware formats

使用 LT LTS L LL LLL LLLL 也可以使用区域设置感知日期和时间格式。它们是在 2.2.1 版本中添加的,除了 LTS 是在 2.8.4 版本中添加的。

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

令牌区分大小写。

Tokens are case-sensitive.

输入示例描述
L09/04/1986日期(本地格式)
LLSeptember 4 1986月份名称、日期、年份
LLLSeptember 4 1986 8:30 PM月份名称、日期、年份、时间
LLLLThursday, September 4 1986 8:30 PM星期几、月份名称、月份中的某一天、年份、时间
LT8:30 PM时间(不含秒)
LTS8:30:00 PM时间(秒)

小时、分钟、秒、毫秒和偏移标记

Hour, minute, second, millisecond, and offset tokens

令牌区分大小写。

Tokens are case-sensitive.

输入示例描述
H HH0..23小时(24 小时制)
h hh1..12小时(与 a A 一起使用的 12 小时时间。)
k kk1..24小时(24 小时制,从 1 到 24)
a Aam pm子午线前后(注意一个字符 a p 也被认为是有效的)
m mm0..59分钟数
s ss0..59秒数
S SS SSS ... SSSSSSSSS0..999999999小数秒
Z ZZ+12:00与 UTC 的偏移量为 +-HH:mm+-HHmmZ

从 2.10.5 版本开始:小数秒标记长度为 4 到 9 可以解析任意数量的数字,但只会考虑前 3 个(毫秒)。如果你的时间打印有很多小数位并且想要使用输入,请使用。

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

请注意,提供的 S 字符数仅在以严格模式解析时才相关。在标准模式下,SSSSSSSSSS 都是等价的,并被解释为秒的小数部分。例如,.12 始终为 120 毫秒,传递 SS 不会导致它被解释为 12 毫秒。

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

Z ZZ 是在 1.2.0 版本中添加的。

Z ZZ were added in version 1.2.0.

S SS SSS 是在 1.6.0 版本中添加的。

S SS SSS were added in version 1.6.0.

X 是在 2.0.0 版本中添加的。

X was added in version 2.0.0.

SSSSS ... SSSSSSSSS 是在 2.10.5 版本中添加的。

SSSSS ... SSSSSSSSS were added in version 2.10.5.

k kk 是在 2.13.0 版本中添加的。

k kk were added in version 2.13.0.

除非你指定时区偏移量,否则解析字符串将在当前时区中创建一个日期。

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

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

纪元年相关令牌

Era Year related tokens

令牌区分大小写。

Tokens are case-sensitive.

输入示例描述
y ..yyyy5 +5 -500年数
yo5th 1st序数年
NAD缩写年号
NNAD缩写年号
NNNAD缩写年号
NNNNAnno Domini全纪元名称
NNNNNAD狭义纪元名称

2.25.0 中添加了时代支持。令牌/API 仍在不断变化。

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

注意事项和陷阱

Notes and gotchas

如果解析输入产生的 moment 不存在,moment#isValid 将返回 false。

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

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

从版本 2.0.0 开始,区域设置键可以作为第三个参数传递给 moment()moment.utc()

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

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

Moment 的解析器非常宽容,这可能会导致不希望的/意外的行为。

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

例如,可以观察到以下行为:

For example, the following behavior can be observed:

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

在 2.13.0 之前,解析器表现出以下行为。这已得到纠正。

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

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

从版本 2.3.0 开始,你可以为最后一个参数指定一个布尔值,以使 Moment 使用严格的解析。严格解析要求格式和输入完全匹配,包括分隔符。

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

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

你可以同时使用语言环境和严格性。

You can use both locale and strictness.

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

严格解析通常是最好的解析选项。有关选择严格与宽松解析的更多信息,请参阅 解析指南。

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

解析两位数年份

Parsing two digit years

默认情况下,68 以上的两位数年份被假定为 1900 年代,68 或以下的年份被假定为 2000 年代。这可以通过替换 moment.parseTwoDigitYear 方法来更改。此方法的唯一参数是一个包含用户输入的两年的字符串,应该以整数形式返回年份。

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

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

解析粘附的小时和分钟

Parsing glued hour and minutes

从版本 2.11.0 开始,支持解析 hmmHmmhmmssHmmss

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

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

字符串 + 多个格式 1.0.0+

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

如果你不知道输入字符串的确切格式,但知道它可能是多种格式中的一种,则可以使用格式数组。

If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.

这与 字符串 + 格式 相同,只是它会尝试将输入匹配为多种格式。

This is the same as String + Format, only it will try to match the input to multiple formats.

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

从版本 2.3.0 开始,Moment 使用一些简单的启发式方法来确定要使用哪种格式。为了:

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

  • 比无效日期更喜欢产生 有效 日期的格式。

    Prefer formats resulting in valid dates over invalid ones.

  • 更喜欢解析更多字符串的格式而不是更少,使用更多格式而不是更少的格式,即更喜欢更严格的解析。

    Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.

  • 优先使用数组中较早的格式而不是较晚的格式。

    Prefer formats earlier in the array than later.

moment("29-06-1995", ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"]); // uses the last format
moment("05-06-1995", ["MM-DD-YYYY", "DD-MM-YYYY"]);          // uses the first format

你还可以指定语言环境和严格性参数。它们的工作方式与单一格式的情况相同。

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

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

注意:解析多种格式比解析一种格式要慢得多。如果能避免的话,解析单一格式会快很多。

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

特殊格式 2.7.0+

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

ISO-8601 是时间和持续时间显示的标准。Moment 已经支持解析 iso-8601 字符串,但这可以在构建 moment 时在格式/格式列表中明确指定。

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

要指定 iso-8601 解析,请使用 moment.ISO_8601 常量。

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

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

从版本 2.20.0 开始,以下 HTML5 格式可用作 moment 对象的 HTML5_FMT 属性 (moment.HTML5_FMT.*) 中的常量:

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

持续的格式示例输入类型
DATETIME_LOCALYYYY-MM-DDTHH:mm2017-12-14T16:34<input type="datetime-local" />
DATETIME_LOCAL_SECONDSYYYY-MM-DDTHH:mm:ss2017-12-14T16:34:10<input type="datetime-local" step="1" />
DATETIME_LOCAL_MSYYYY-MM-DDTHH:mm:ss.SSS2017-12-14T16:34:10.234<input type="datetime-local" step="0.001" />
DATEYYYY-MM-DD2017-12-14<input type="date" />
TIMEHH:mm16:34<input type="time" />
TIME_SECONDSHH:mm:ss16:34:10<input type="time" step="1" />
TIME_MSHH:mm:ss.SSS16:34:10.234<input type="time" step="0.001" />
WEEKGGGG-[W]WW2017-W50<input type="week" />
MONTHYYYY-MM2017-12<input type="month" />

对象 2.2.1+

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

你可以通过指定对象中的某些单位来创建 moment。

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

省略的单位默认为 0 或当前日期、月份和年份。

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

daydate 键都表示每月的日期。

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

date 是在 2.8.4 中添加的。

date was added in 2.8.4.

从版本 2.11.0 开始支持字符串值(如最后一行所示)。

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

请注意,与 moment(Array)new Date(year, month, date) 一样,月份的索引为 0。

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

Unix 时间戳(毫秒) 1.0.0+

moment(Number);

new Date(Number) 类似,你可以通过传递表示自 Unix 纪元(1970 年 1 月 1 日 12AM UTC)以来的毫秒数的整数值来创建 moment。

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(1318781876406);

注意:ECMAScript 将此称为 "时间值"

Note: ECMAScript calls this a "Time Value"

Unix 时间戳(秒) 1.6.0+

moment.unix(Number)

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

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

var day = moment.unix(1318781876);

这是作为 moment(timestamp * 1000) 实现的,因此包括输入时间戳中的部分秒数。

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

var day = moment.unix(1318781876.721);

注意:尽管 Unix 时间戳是基于 UTC 的,但这个函数在本地模式下创建了一个 moment 对象。如果你需要 UTC,则随后调用 .utc(),如:

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

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

日期 1.0.0+

moment(Date);

你可以使用预先存在的原生 Javascript Date 对象创建 Moment

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

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

这克隆了 Date 对象;Date 的进一步更改不会影响 Moment,反之亦然。

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

数组 1.0.0+

moment(Number[]);

你可以使用一组反映传递给 new Date() 的参数的数字来创建 moment

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

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

moment([2010, 1, 14, 15, 25, 50, 125]); // February 14th, 3:25:50.125 PM

超过年份的任何值都是可选的,并且默认为可能的最小数字。

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

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

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

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

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

注意:因为这反映了原生 Date 参数,所以月份、小时、分钟、秒和毫秒都是零索引。年份和月份中的日期为 1 索引。

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!

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

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

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

ASP.NET JSON 日期 1.3.0+

moment(String);

默认情况下,Microsoft Web API 以正确的 ISO-8601 格式返回 JSON 日期,但较旧的 ASP.NET 技术可能以 /Date(1198908717056)//Date(1198908717056-0700)/ 形式返回 JSON 中的日期

Microsoft Web API returns JSON dates in proper ISO-8601 format by default, but older ASP.NET technologies may return dates in JSON as /Date(1198908717056)/ or /Date(1198908717056-0700)/

如果传入符合这种格式的字符串,就会被正确解析。

If a string that matches this format is passed in, it will be parsed correctly.

moment("/Date(1198908717056-0700)/"); // 2007-12-28T23:11:57.056-07:00

Moment 克隆 1.2.0+

moment(Moment);

所有 moment 都是可变的。如果你想要一个 moment 的克隆,你可以隐式或显式地这样做。

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

稍后调用 moment() 将克隆它。

Calling moment() on a moment will clone it.

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

此外,你可以调用 moment#clone 来克隆 moment。

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

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

UTC 1.5.0+

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

默认情况下,moment 以本地时间解析和显示。

By default, moment parses and displays in local time.

如果要解析或显示 UTC 时间,可以使用 moment.utc() 而不是 moment()

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

这给我们带来了 Moment.js 的一个有趣的特性。UTC 模式。

This brings us to an interesting feature of Moment.js. UTC mode.

在 UTC 模式下,所有显示方式都将以 UTC 时间显示,而不是本地时间。

While in UTC mode, all display methods will display in UTC time instead of local time.

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

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

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

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

重要的是要注意,尽管上面的显示不同,但它们都是同一 moment。

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

使用 moment.utc() 创建的任何 moment 都将采用 UTC 模式,而使用 moment() 创建的任何 moment 都不会。

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

要从 UTC 切换到本地时间,你可以使用 moment#utcmoment#local

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

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

parseZone 2.3.0+

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

Moment 的字符串解析函数(如 moment(string)moment.utc(string))接受提供的偏移信息,但将生成的 Moment 对象转换为本地或 UTC 时间。相反,moment.parseZone() 解析字符串,但将生成的 Moment 对象保存在固定偏移时区中,并在字符串中提供偏移量。

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

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

它还允许你传递语言环境和严格性参数。

It also allows you to pass locale and strictness arguments.

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

moment.parseZone 相当于解析字符串,用 moment#utcOffset 解析 zone。

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

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

验证 1.7.0+

moment().isValid();

Moment 应用比 Date 构造函数更严格的初始化规则。

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'

你可以使用 moment#isValid 检查 Moment 是否认为日期无效。你可以使用返回对象的 moment#parsingFlags 检查 #isValid 使用的指标。

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:日期字段溢出,例如第 13 个月、第 32 天(或非闰年的 2 月 29 日)、第 367 天等。overflow 包含无效单位的索引 匹配 #invalidAt(见下文);-1 表示没有溢出。

    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:无效的月份名称,例如 moment('Marbruary', 'MMMM');。包含无效的月份字符串本身,否则为空。

    invalidMonth: An invalid month name, such as moment('Marbruary', 'MMMM');. Contains the invalid month string itself, or else null.

  • empty:不包含任何可解析内容的输入字符串,例如 moment('this is nonsense');。布尔值。

    empty: An input string that contains nothing parsable, such as moment('this is nonsense');. Boolean.

  • nullInputnull 输入,如 moment(null);。布尔值。

    nullInput: A null input, like moment(null);. Boolean.

  • invalidFormat:一个空的格式列表,例如 moment('2013-05-25', [])。布尔值。

    invalidFormat: An empty list of formats, such as moment('2013-05-25', []). Boolean.

  • userInvalidated:明确创建为无效的日期,例如 moment.invalid()。布尔值。

    userInvalidated: A date created explicitly as invalid, such as moment.invalid(). Boolean.

除了上述内容之外,从 2.13.0 开始,meridiem 和 parsedDateParts 标志一起工作来确定日期有效性。

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

  • meridiem:指示解析了什么子午线 (AM/PM),如果有的话。字符串。

    meridiem: Indicates what meridiem (AM/PM) was parsed, if any. String.

  • parsedDateParts:返回按降序解析的日期部分数组 - 即 parsedDateParts[0] === year。如果不存在任何部分,但 meridiem 具有值,则日期无效。数组。

    parsedDateParts: Returns an array of date parts parsed in descending order - i.e. parsedDateParts[0] === year. If no parts are present, but meridiem has value, date is invalid. Array.

此外,如果在严格模式下解析 Moment,则这些标志必须为空才能使 Moment 有效:

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

  • unusedTokens:在输入字符串中找不到格式子字符串数组

    unusedTokens: array of format substrings not found in the input string

  • unusedInput:与格式字符串不匹配的输入子字符串数组

    unusedInput: array of input substrings not matched to the format string

注意:Moment 的有效性概念在 2.2 和 2.3 之间变得更加严格和一致。注意:有效性取决于 moment 创建。修改后的 moment(即 moment().hour(NaN))将保持有效。

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

此外,你可以使用 moment#invalidAt 确定溢出的日期单位。

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

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

返回值含义如下:

The return value has the following meaning:

  1. 年数

    years

  2. 月数

    months

  3. 天数

    days

  4. 小时数

    hours

  5. 分钟数

    minutes

  6. 秒数

    seconds

  7. 毫秒数

    milliseconds

注意:如果有多个错误单位,则返回第一个单位(例如,因为天数有效性可能取决于月份)。

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

无效 moment

Invalid Moments

如果某个 moment 无效,则它在浮点运算中的行为类似于 NaN。

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

以下所有内容都会产生无效 moment:

All of the following produce invalid moments:

  • invalid.add(unit, value)

  • another.add(invalid)

  • invalid.clone()

  • invalid.diff(another)

  • invalid.endOf(unit)

  • invalid.max(another)

  • another.max(invalid)

  • invalid.min(another)

  • another.min(invalid)

  • invalid.set(unit, value)

  • invalid.startOf(unit)

  • invalid.subtract(unit, value)

以下生成 'InvalidDate' 的本地化版本:

The following produce a localized version of 'InvalidDate':

  • invalid.format(anyFmt) 在当前语言环境中产生 'Invalid Date'

    invalid.format(anyFmt) results in 'Invalid Date' in the current locale

  • invalid.from(another)

  • another.from(invalid)

  • invalid.fromNow(suffix)

  • invalid.to(another)

  • another.to(invalid)

  • invalid.toNow(suffix)

  • invalid.toISOString()(2.18.0 之前)

    invalid.toISOString() (Before 2.18.0)

  • invalid.toString()

以下返回 false

The following return false:

  • invalid.isAfter(another)

  • invalid.isAfter(invalid)

  • another.isAfter(invalid)

  • invalid.isBefore(another)

  • invalid.isBefore(invalid)

  • another.isBefore(invalid)

  • invalid.isBetween(another, another)

  • invalid.isBetween(invalid, invalid)

  • invalid.isSame(another)

  • invalid.isSame(invalid)

  • another.isSame(invalid)

  • invalid.isSameOrAfter(another)

  • invalid.isSameOrAfter(invalid)

  • another.isSameOrAfter(invalid)

  • invalid.isSameOrBefore(another)

  • invalid.isSameOrBefore(invalid)

  • another.isSameOrBefore(invalid)

这些返回具有某种结构的 nullNaN

And these return null or NaN with some structure:

  • invalid.get(unit) 返回 null,与所有其他命名的 getter 一样

    invalid.get(unit) returns null, as all other named getters

  • invalid.toArray() === [NaN, NaN, NaN, NaN, NaN, NaN]

  • invalid.toObject() 的所有值都设置为 NaN

    invalid.toObject() has all values set to NaN

  • invalid.toDate() 返回无效的日期对象

    invalid.toDate() returns an invalid Date object

  • invalid.toJSON() 返回空值

    invalid.toJSON() returns null

  • invalid.unix() 返回空值

    invalid.unix() returns null

  • invalid.valueOf() 返回空值

    invalid.valueOf() returns null

  • invalid.toISOString() 返回 null(自 2.18.0 起)

    invalid.toISOString() returns null (As of 2.18.0)

创建数据 2.11.0+

moment().creationData();

创建 moment 对象后,可以使用 creationData() 方法访问所有输入:

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

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

默认值 2.2.1+

moment("15", "hh")

你可以创建一个仅指定部分单位的 moment 对象,其余单位将默认为当前日、月或年,或 0 表示小时、分钟、秒和毫秒。

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

默认为现在,当没有传递任何内容时:

Defaulting to now, when nothing is passed:

moment();  // current date and time

默认为今天,当只传递小时、分钟、秒和毫秒时:

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

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

默认为这个月和年,当只传递天数和更小的单位时:

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

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

如果未指定年份,则默认为今年:

Defaulting to this year, if year is not specified:

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

Moment.js 使用重载的 getter 和 setter。你可能熟悉这种模式在 jQuery 中的使用。

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

调用这些不带参数的方法充当 getter,带参数调用它们充当 setter。

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

这些映射到原生 Date 对象上的相应函数。

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

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

如果你在 UTC 模式,它们将映射到等效的 UTC。

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

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

为了方便起见,从版本 2.0.0 开始,方法名称同时存在单数和复数。

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

注意:所有这些方法在用作设置器时都会改变原始 moment。

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

注意:从 2.19.0 开始,将 NaN 传递给任何 setter 都是无操作的。在 2.19.0 之前,它以错误的方式使该 moment 无效。

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

毫秒 1.3.0+

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

获取或设置毫秒数。

Gets or sets the milliseconds.

接受从 0 到 999 的数字。如果超出范围,它将冒泡到秒。

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

1.0.0+

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

获取或设置秒数。

Gets or sets the seconds.

接受从 0 到 59 的数字。如果超出范围,它将冒泡到分钟。

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

分钟 1.0.0+

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

获取或设置分钟。

Gets or sets the minutes.

接受从 0 到 59 的数字。如果超出范围,它将冒泡到小时。

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

小时 1.0.0+

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

获取或设置小时。

Gets or sets the hour.

接受从 0 到 23 的数字。如果超出范围,它将冒泡到天。

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

日期 1.0.0+

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

获取或设置月中的第几天。

Gets or sets the day of the month.

接受从 1 到 31 的数字。如果超出范围,它将冒泡到月。

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

注意:Moment#date 表示月份的日期,Moment#day 表示星期几。

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

注意:如果你链接多个动作来构造一个日期,你应该从一年开始,然后是一个月,然后是一天等。否则你可能会得到意想不到的结果,比如 day=31 和当前月份只有 30 天(这同样适用于原生 JavaScript Date 操作),返回的日期将是当月的 30 号(更多详细信息请参阅 月份)。

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

不好的:moment().date(day).month(month).year(year)

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

好的:moment().year(year).month(month).date(day)

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

2.16.0 已弃用,使用 moment().dates()。请改用 moment().date()

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

星期 1.3.0+

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

获取或设置星期几。

Gets or sets the day of the week.

该方法可用于设置星期几,星期日为 0,星期六为 6。

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

如果给定的值是从 0 到 6,则结果日期将在当前(星期日到星期六)周内。

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

如果超出范围,它将冒泡到其他周。

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

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

注意:Moment#date 表示月份的日期,Moment#day 表示星期几。

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

从 2.1.0 开始,还支持日期名称。这是在当前的语言环境中解析的。

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");

星期(区域设置感知) 2.1.0+

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

根据区域设置获取或设置星期几。

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

如果语言环境将星期一指定为一周的第一天,则 moment().weekday(0) 将为星期一。如果星期日是一周的第一天,则 moment().weekday(0) 将是星期日。

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.

moment#day 一样,如果超出范围,就会冒泡到其他周。

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

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

ISO 星期 2.1.0+

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

获取或设置 ISO 星期1 为星期一,7 为星期日。

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

moment#day 一样,如果超出范围,就会冒泡到其他周。

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

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

还支持日期名称。这是在当前的语言环境中解析的。

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

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

年积日 2.0.0+

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

获取或设置一年中的第几天。

Gets or sets the day of the year.

接受从 1 到 366 的数字。如果超出范围,它将冒泡到年份。

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

2.0.0+

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

获取或设置一年中的第几周。

Gets or sets the week of the year.

因为不同的语言环境定义一年中的星期编号不同,Moment.js 添加了 moment#week 来获取/设置一年中的本地化星期。

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.

例如,在美国,星期日是一周的第一天。1 月 1 日所在的那一周是一年中的第一周。

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.

在法国,星期一是一周的第一天,1 月 4 日所在的那一周是一年的第一周。

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

此时 moment#week 的输出将取决于 locale

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

设置一年中的第几周时,保留星期几。

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

周 (ISO) 2.0.0+

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

获取或设置 一年中的 ISO 周

Gets or sets the ISO week of the year.

设置一年中的第几周时,保留星期几。

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

月份 1.0.0+

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

获取或设置月份。

Gets or sets the month.

接受从 0 到 11 的数字。如果超出范围,它将冒泡到年份。

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

注意:月份是零索引的,所以一月是第 0 个月。

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

从 2.1.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");

在 2.1.0 版本之前,如果某个 moment 更改了月份,并且新月份没有足够的天数来保留当月的当前日期,则会溢出到下个月。

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.

从版本 2.1.0 开始,该值已更改为固定到目标月末。

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

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

2.16.0 已弃用,使用 moment().months()。请改用 moment().month()

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

季度 2.6.0+

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

获取季度(1 到 4)。

Gets the quarter (1 to 4).

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

设置季度(1 到 4)。

Sets the quarter (1 to 4).

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

年份 1.0.0+

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

获取或设置年份。

Gets or sets the year.

接受从 -270,000 到 270,000 的数字。

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

2.6.0 已弃用使用 moment().years()。请改用 moment().year()

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

周年 2.1.0+

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

根据区域设置获取或设置周年。

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

因为第一周的第一天并不总是在一年的第一天,所以有时周年与月年不同。

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

例如,在美国,包含 1 月 1 日的那一周始终是第一周。在美国,星期也从星期日开始。如果 1 月 1 日是星期一,则 12 月 31 日将与 1 月 1 日属于同一周,因此与 1 月 1 日属于同一周年。12 月 30 日的星期与 12 月 31 日不同。

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.

周数 2.6.0+

moment().weeksInYear();

根据当前 moment 所在年份的区域设置获取周数。

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

周数 (ISO) 2.6.0+

moment().isoWeeksInYear();

根据 周数,获取当前 moment 所在年份的周数。

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

取值 2.2.1+

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

字符串获取器。一般来说

String getter. In general

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

单位不区分大小写,并支持复数和缩写形式:年(years,y),月(months,M),日期(dates,D),小时(hours,h),分钟(minutes,m),秒(seconds,s),毫秒(milliseconds,ms)。

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

赋值 2.2.1+

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

通用设置器,接受单位作为第一个参数,值作为第二个参数:

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

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

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

单位不区分大小写,并支持复数和缩写形式:年(years,y),月(months,M),日期(dates,D),小时(hours,h),分钟(minutes,m),秒(seconds,s),毫秒(milliseconds,ms)。

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

2.9.0 中添加了对象解析

Object parsing was added in 2.9.0

最大值 2.7.0+

moment.max(Moment[,Moment...]);
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);  // b

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

如果没有参数,该函数将返回一个具有当前时间的 moment 实例。

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

从版本 2.10.5 开始,如果参数之一为无效 moment,则结果为无效 moment。

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

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

最小值 2.7.0+

moment.min(Moment[,Moment...]);
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);  // a
moment.min([a, b]); // a

如果没有参数,该函数将返回一个具有当前时间的 moment 实例。

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

从版本 2.10.5 开始,如果参数之一为无效 moment,则结果为无效 moment。

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

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

拥有 Moment 后,你可能想以某种方式操纵它。有许多方法可以帮助解决这个问题。

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 使用 流式接口模式,也称为 方法链。这允许你做如下疯狂的事情。

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

moment().add(7, 'days').subtract(1, 'months').year(2009).hours(0).minutes(0).seconds(0);

注意:应该注意的是,moment 是可变的。调用任何操作方法都会改变原始 moment。

Note: It should be noted that moments are mutable. Calling any of the manipulation methods will change the original moment.

如果要创建副本并对其进行操作,则应在操作 moment 之前使用 moment#clone有关克隆的更多信息。

If you want to create a copy and manipulate it, you should use moment#clone before manipulating the moment. More info on cloning.

加法 1.0.0+

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

通过添加时间来改变原始 moment。

Mutates the original moment by adding time.

这是一个非常强大的功能,可以为现有 moment 添加时间。要添加时间,请传递要添加的时间和要添加的数量的键。

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');
速记
年数 y
季度 Q
月数 M
周数 w
天数 d
小时数 h
分钟数 m
秒数 s
毫秒数 ms

如果你想同时添加多个不同的键,你可以将它们作为对象字面量传入。

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

moment().add(7, 'days').add(1, 'months'); // with chaining
moment().add({days:7,months:1}); // with object literal

数量没有上限,因此你可以重载任何参数。

There are no upper limits for the amounts, so you can overload any of the parameters.

moment().add(1000000, 'milliseconds'); // a million milliseconds
moment().add(360, 'days'); // 360 days

月份和年份的特殊考虑

Special considerations for months and years

如果原始日期的月份日期大于最后一个月的天数,则该月的日期将更改为最后一个月的最后一天。

If the day of the month on the original date is greater than the number of days in the final month, the day of the month will change to the last day in the final month.

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

添加跨越夏令时的时间时,还需要牢记一些特殊注意事项。如果你要添加年、月、周或日,则原始小时将始终与添加的小时匹配。

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

添加一个月会将指定的月数添加到日期。

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

moment([2010, 1, 28]);                 // February 28
moment([2010, 1, 28]).add(1, 'month'); // March 28
var m = moment(new Date(2011, 2, 12, 5, 0, 0)); // the day before DST in the US
m.hours(); // 5
m.add(1, 'days').hours(); // 5

如果你要添加小时、分钟、秒或毫秒,假设你希望精确到小时,并且会导致不同的小时。

If you are adding hours, minutes, seconds, or milliseconds, the assumption is that you want precision to the hour, and will result in a different hour.

var m = moment(new Date(2011, 2, 12, 5, 0, 0)); // the day before DST in the US
m.hours(); // 5
m.add(24, 'hours').hours(); // 6 (but you may have to set the timezone first)

或者,你可以使用 时长 添加到 moment。

Alternatively, you can use durations to add to moments.

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

在 2.8.0 版本之前,还支持 moment#add(String, Number) 语法。它已被弃用,取而代之的是 moment#add(Number, String)

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

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

从 2.12.0 开始,当传递天和月的小数值时,它们将四舍五入到最接近的整数。周、季度和年转换为天或月,然后四舍五入为最接近的整数。

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

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

减法 1.0.0+

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

通过减去时间来改变原始 moment。

Mutates the original moment by subtracting time.

这和 moment#add 完全一样,只是不是加了时间,而是减了时间。

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

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

在 2.8.0 版本之前,还支持 moment#subtract(String, Number) 语法。它已被弃用,取而代之的是 moment#subtract(Number, String)

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

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

从 2.12.0 开始,当传递天和月的小数值时,它们将四舍五入到最接近的整数。周、季度和年转换为天或月,然后四舍五入为最接近的整数。

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

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

请注意,为了使运算 moment.add(-.5, 'days')moment.subtract(.5, 'days') 等效,-.5、-1.5、-2.5 等会向下舍入。

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

时间开端 1.7.0+

moment().startOf(String);

通过将其设置为一个时间单位的开始来改变原始 moment。

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

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

这些快捷方式与以下基本相同。

These shortcuts are essentially the same as the following.

moment().startOf('year');
moment().month(0).date(1).hours(0).minutes(0).seconds(0).milliseconds(0);
moment().startOf('hour');
moment().minutes(0).seconds(0).milliseconds(0)

从版本 2.0.0 开始,moment#startOf('day') 取代了 moment#sod

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

注意:moment#startOf('week') 是在 2.0.0 版本中添加的。

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

从版本 2.1.0 开始,moment#startOf('week') 使用区域设置感知周开始日。

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

注意:moment#startOf('isoWeek') 是在 2.2.0 版本中添加的。

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

注意:在 2.13.0 中添加了 moment#startOf('date') 作为日期的别名

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

时间终端 1.7.0+

moment().endOf(String);

通过将原始 moment 设置为时间单位的结束来改变原始 moment。

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

这点和 moment#startOf 一样,只是不是设置为单位时间的开始,而是设置为单位时间的结束。

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

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

从版本 2.0.0 开始,moment#endOf('day') 取代了 moment#eod

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

注意:moment#endOf('week') 是在 2.0.0 版本中添加的。

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

从版本 2.1.0 开始,moment#endOf('week') 使用区域设置感知周开始日。

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

最大值 开始于 2.1.0,弃用于 2.7.0

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

注意:该函数在 2.7.0 中已被弃用。请考虑 moment.min

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


将 moment 限制为另一个 moment 值的最大值。所以 a.max(b)a = moment.min(a, b) 相同(注意 max 转换为 min)。

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

有时,服务器时钟与客户端时钟不太同步。这最终会显示人性化的字符串,例如 "in a few seconds" 而不是 "a few seconds ago"。你可以使用 moment#max() 来防止这种情况发生:

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

这是 moment#min 的对应物。

This is the counterpart for moment#min.

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

你可以将要传递给 moment() 的任何内容传递给 moment#max

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

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

最小值 开始于 2.1.0,弃用于 2.7.0

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

注意:该函数在 2.7.0 中已被弃用。请考虑 moment.max

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


将 moment 限制为另一个 moment 值的最小值。所以 a.min(b)a = moment.max(a, b) 相同(注意 min 转换为 max)。

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

这是 moment#max 的对应物。

This is the counterpart for moment#max.

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

这可以与 moment#max 结合使用以将 moment 限制在一个范围内。

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

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

本地 1.5.0+

moment().local();
moment().local(Boolean); // from 2.8.0

在原始 moment 设置标志以使用本地时间显示 moment 而不是原始 moment 的时间。

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

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

Local 也可用于转换出固定偏移模式:

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

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

传递 true 将更改时区而不更改当前时间。

Passing true will change the time zone without changing the current time.

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

有关 UTC 模式的更多信息,请参阅 moment.utc()

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

UTC 1.5.0+

moment().utc();
moment().utc(Boolean); // from 2.8.0

在原始 moment 设置标志以使用 UTC 显示 moment 而不是原始 moment 的时间。

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

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

UTC 也可用于转换出固定偏移量模式:

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

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

传递 true 将更改时区而不更改当前时间。

Passing true will change the time zone without changing the current time.

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

有关 UTC 模式的更多信息,请参阅 moment.utc()

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

UTC 偏移 2.9.0++

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

以分钟为单位获取或设置 UTC 偏移量。

Get or set the UTC offset in minutes.

注意:与 moment.fn.zone 不同,此函数返回 UTC 的实际偏移量,而不是反向偏移量(由 Date.prototype.getTimezoneOffset 返回)。

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

获取当前对象的 utcOffset

Getting the utcOffset of the current object:

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

通过提供分钟来设置 UTC 偏移量。偏移量设置在调用 utcOffset() 的 moment 对象上。如果你想全局设置偏移量,请尝试使用 moment-timezone。请注意,一旦你设置了偏移量,它就是固定的并且不会自行更改(即没有 DST 规则)。如果你想要一个实际时区 - 特定位置的时间,例如 America/Los_Angeles,请考虑 moment-timezone

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

moment().utcOffset(120);

如果输入小于 16 且大于 -16,它会将你的输入解释为小时数。

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

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

也可以设置字符串的 UTC 偏移量。

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

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

moment#utcOffset 将在字符串中搜索 +00 -00 +00:00 +0000 -00:00 -0000 Z 的最后一个匹配项,因此你甚至可以传递带偏移量的 ISO8601 格式的字符串,moment 将更改为该 UTC 偏移量。

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

请注意,如果字符串不包含 'Z',则它必须包含 +- 字符。

Note that if the string does not include 'Z', it must include the + or - character.

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

utcOffset 函数有一个可选的第二个参数,它接受一个布尔值,指示是否保留一天中的现有时间。

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

  • 传递 false(默认值)将在世界时保持相同 moment,但本地时间会改变。

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

  • 通过 true 将保持相同的本地时间,但代价是选择不同的世界时间点。

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

此特性的一种用途是,如果你想仅使用数字输入值来构建具有特定时区偏移量的 moment:

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

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

时区偏移 From 1.2.0, deprecated 2.9.0+

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

注意:该函数在 2.9.0 中已被弃用。请考虑 moment.fn.utcOffset

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

以分钟为单位获取时区偏移量。

Get the time zone offset in minutes.

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

从版本 2.1.0 开始,可以通过传入距 GMT 的分钟数偏移来设置偏移量。

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);

如果输入小于 16 且大于 -16,它会将你的输入解释为小时数。

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

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

也可以从字符串设置区域。

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

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

moment#zone 将在字符串中搜索 +00:00 +0000 -00:00 -0000 的第一个匹配项,因此你甚至可以传递 ISO8601 格式的字符串,moment 将更改为该区域。

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

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

解析和操作完成后,你需要某种方式来显示 moment。

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

格式 1.0.0+

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

这是最强大的显示选项。它接受一串标记并将它们替换为相应的值。

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

moment().format();                                // "2014-09-08T08:02:17-05:00" (ISO 8601, no fractional seconds)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
moment().format("ddd, hA");                       // "Sun, 3PM"
moment().format("[Today is] dddd");               // "Today is Sunday"
moment('gibberish').format('YYYY MM DD');         // "Invalid date"
令牌 输出
月份 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
季度 Q 1 2 3 4
Qo 1st 2nd 3rd 4th
每月的某一天 D 1 2 ...30 31
Do 1st 2nd ...30th 31st
DD 01 02 ...30 31
年积日 DDD 1 2 ...364 365
DDDo 1st 2nd ...364th 365th
DDDD 001 002 ...364 365
星期 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
星期几(区域设置) e 0 1 ...5 6
星期几 (ISO) E 1 2 ...6 7
w 1 2 ...52 53
wo 1st 2nd ...52nd 53rd
ww 01 02 ...52 53
周 (ISO) W 1 2 ...52 53
Wo 1st 2nd ...52nd 53rd
WW 01 02 ...52 53
年份 YY 70 71 ...29 30
YYYY 1970 1971 ...2029 2030
YYYYYY -001970 -001971 ...+001907 +001971
注意: 延长年限(涵盖自 1970 年 1 月 1 日起向前或向后约 273,790 年的完整时间值范围)
Y 1970 1971 ...9999 +10000 +10001
注意: 这符合 ISO 8601 标准,适用于 9999 年之后的日期
纪元年份 y 1 2 ...2020 ...
时代 N, NN, NNN BC AD
注意: 缩写年号
NNNN 在基督之前,Anno Domini
注意: 完整时代名称
NNNNN BC AD
注意: 狭义年号
周年 gg 70 71 ...29 30
gggg 1970 1971 ...2029 2030
周年 (ISO) GG 70 71 ...29 30
GGGG 1970 1971 ...2029 2030
AM/PM A AM PM
a am pm
小时 H 0 1 ...22 23
HH 00 01 ...22 23
h 1 2 ...11 12
hh 01 02 ...11 12
k 1 2 ...23 24
kk 01 02 ...23 24
分钟 m 0 1 ...58 59
mm 00 01 ...58 59
s 0 1 ...58 59
ss 00 01 ...58 59
小数秒 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..]
时区 z 或 zz EST CST ...MST PST
注意:1.6.0 开始,z/zz 格式标记已从普通 moment 对象中弃用。 在这里阅读更多相关信息。 但是,如果你使用带有 moment-timezone 插件的特定时区,它们确实可以工作。
Z -07:00 -06:00 ...+06:00 +07:00
ZZ -0700 -0600 ...+0600 +0700
Unix 时间戳 X 1360013296
Unix 毫秒时间戳 x 1360013296123

X 是在 2.0.0 中添加的。

X was added in 2.0.0.

e E gg gggg GG GGGG 是在 2.1.0 中添加的。

e E gg gggg GG GGGG were added in 2.1.0.

x 是在 2.8.4 中添加的。

x was added in 2.8.4.

SSSSSSSSSSSSS 是 2.10.5 中添加的。它们显示 3 位有效数字,其余数字用零填充。

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

kkk 是在 2.13.0 中添加的。

k and kk were added in 2.13.0.

本地化格式

Localized formats

由于首选格式因区域设置而异,因此有一些标记可用于根据区域设置格式化 moment。

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.

时间 LT 8:30 PM
时间以秒为单位 LTS 8:30:25 PM
月份数字、月份日期、年份 L 09/04/1986
l 9/4/1986
月份名称、日期、年份 LL September 4, 1986
ll Sep 4, 1986
月份名称、日期、年份、时间 LLL September 4, 1986 8:30 PM
lll Sep 4, 1986 8:30 PM
月份名称、月份、星期、年份、时间 LLLL Thursday, September 4, 1986 8:30 PM
llll Thu, Sep 4, 1986 8:30 PM

l ll lll llll 在 2.0.0 中可用。LTS 是在 2.8.4 中添加的。

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

转义字符

Escaping characters

要转义格式字符串中的字符,可以将字符括在方括号中。

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

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

与 LDML 的异同

Similarities and differences with LDML

注意:虽然这些日期格式与 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.

其他令牌

Other tokens

如果你更喜欢使用 strftime 而不是类似 LDML 的解析标记,则可以使用 Ben Oakes 的插件。benjaminoakes/moment-strftime

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

调用没有格式的 moment#format 将默认为 moment.defaultFormat。开箱即用,moment.defaultFormat 是 ISO8601 格式 YYYY-MM-DDTHH:mm:ssZ

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.

从版本 2.13.0 开始,在 UTC 模式下,默认格式由 moment.defaultFormatUtc 控制,其格式为 YYYY-MM-DDTHH:mm:ss[Z]。这将返回 Z 作为偏移量,而不是 +00:00

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

在某些情况下,本地时区(例如 Atlantic/Reykjavik)可能具有零偏移量,并且将被视为 UTC。在这种情况下,将 moment.defaultFormatmoment.defaultFormatUtc 设置为使用相同的格式可能会很有用。

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

改变 moment.defaultFormat 的值只会影响格式化,不会影响解析。例如:

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

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

从此刻到过去的时间 1.0.0+

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

一种常用的显示时间的方式由 moment#fromNow 处理。这有时称为时间距离或相对时间。

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

如果传 true,可以得到不带后缀的值。

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

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

基本字符串是 由当前语言环境定制。时间四舍五入到最接近的秒数。

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

下表概述了每个时间长度显示哪个字符串的细目。

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

范围 示例输出
0 到 44 秒 s a few seconds ago
未设置 ss 44 seconds ago
45 至 89 秒 m a minute ago
90 秒到 44 分钟 mm 2 minutes ago ...44 minutes ago
45 至 89 分钟 h an hour ago
90 分钟到 21 小时 hh 2 hours ago ...21 hours ago
22 至 35 小时 d a day ago
36 小时至 25 天 dd 2 days ago ...25 days ago
26 至 45 天 M a month ago
45 至 319 天 MM 2 months ago ...10 months ago
320 至 547 天(1.5 年) y a year ago
548 天+ yy 2 years ago ...20 years ago

注意:从版本 2.10.3 开始,如果目标 moment 对象无效,则结果是本地化的无效日期字符串。

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

注意:ss 键是在 2.18.0 中添加的。这是一个可选的阈值。它永远不会显示,除非用户手动设置 ss 阈值。在设置 ss 阈值之前,它默认为 s 阈值减 1(因此,对用户不可见)。

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

从 X 到过去的时间 1.0.0+

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

你可能想要显示与现在以外的时间相关的 moment。在这种情况下,你可以使用 moment#from

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"

第一个参数是你可以传递给 moment() 或实际的 Moment 的任何内容。

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"

moment#fromNow 一样,将 true 作为第二个参数传递会返回不带后缀的值。这在任何需要人类可读时间长度的地方都很有用。

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"

从版本 2.10.3 开始,如果任何端点无效,则结果是本地化的无效日期字符串。

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);

一种常用的显示时间的方式由 moment#toNow 处理。这有时称为时间距离或相对时间。

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

这类似于 moment.fromNow,但给出了相反的区间:a.fromNow() = - a.toNow()

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

这类似于 moment.to,但针对当前时间是特殊情况。如果要控制区间的两个端点,使用 moment.to

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

如果传 true,可以得到没有前缀的值。

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

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

基本字符串是 由当前语言环境定制

The base strings are customized by the current locale.

下表概述了每个时间长度显示哪个字符串的细目。

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

范围 示例输出
0 到 44 秒 s in seconds
45 至 89 秒 m in a minute
90 秒到 44 分钟 mm in 2 minutes ...in 44 minutes
45 至 89 分钟 h in an hour
90 分钟到 21 小时 hh in 2 hours ...in 21 hours
22 至 35 小时 d in a day
36 小时至 25 天 dd in 2 days ...in 25 days
26 至 45 天 M in a month
45 至 319 天 MM in 2 months ...in 10 months
320 至 547 天(1.5 年) y in a year
548 天+ yy in 2 years ...in 20 years

从版本 2.10.3 开始,如果目标 moment 对象无效,则结果是本地化的无效日期字符串。

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

从 X 到未来的时间 2.10.3+

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

你可能想要显示与现在以外的时间相关的 moment。在这种情况下,你可以使用 moment#to

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"

第一个参数是你可以传递给 moment() 或实际的 Moment 的任何内容。

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"

moment#toNow 一样,将 true 作为第二个参数传递会返回不带后缀的值。这在任何需要人类可读时间长度的地方都很有用。

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"

从版本 2.10.3 开始,如果任何端点无效,则结果是本地化的无效日期字符串。

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(referenceDay);
moment().calendar(referenceDay, formats);  // from 2.10.5
moment().calendar(formats);  // from 2.25.0

日历时间显示相对于给定 referenceDay 的时间(默认为今天的开始),但与 moment#fromNow 略有不同。

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

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

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

上个星期 Last Monday at 2:30 AM
前一天 Yesterday at 2:30 AM
同一天 Today at 2:30 AM
第二天 Tomorrow at 2:30 AM
下个星期 Sunday at 2:30 AM
其他 7/10/2011

这些字符串是本地化的,并且是 可以定制

These strings are localized, and can be customized.

从 2.10.5 开始,支持指定每次调用的日历输出格式:

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'
});

当 moment 距离 referenceDay 超过一周时,sameElse 用作格式

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

注意:从版本 2.14.0 开始,日历的格式参数可以是在 moment 上下文中使用单个参数执行的回调:

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

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

注意:从版本 2.25.0 开始,你只能传递一个格式参数,它可以是字符串和函数的对象:

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

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

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

时间差 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);

要获得以毫秒为单位的差异,请像使用 moment#from 一样使用 moment#diff

To get the difference in milliseconds, use moment#diff like you would use moment#from.

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000

要获得另一个测量单位的差异,请将该测量值作为第二个参数传递。

To get the difference in another unit of measurement, pass that measurement as the second argument.

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

要获得两个 moment 之间差异的持续时间,你可以将 diff 作为参数传递给 moment#duration。有关详细信息,请参阅 moment#duration 上的文档。

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

支持的测量是 yearsmonthsweeksdayshoursminutesseconds。为了便于开发,从 2.0.0 开始支持单数形式。版本 1.1.1 中提供了除毫秒以外的测量单位。

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.

默认情况下,moment#diff 会将结果截断为零位小数,返回一个整数。如果你想要一个浮点数,传递 true 作为第三个参数。在 2.0.0 之前,moment#diff 返回四舍五入到最接近的整数的数字,而不是截断的数字。

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

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

如果这个 moment 早于你传递给 moment.fn.diff 的 moment,则返回值为负数。

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

想到这一点的一个简单方法是用减号运算符替换 .diff(

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

          // a < b
a.diff(b) // a - b < 0
b.diff(a) // b - a > 0

年月差

Month and year diffs

moment#diff 对月份和年份的差异有一些特殊处理。它经过优化以确保具有相同日期的两个月始终相隔一个整数。

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.

所以 1 月 15 日到 2 月 15 日应该正好是 1 个月。

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

2 月 28 日到 3 月 28 日应该正好是 1 个月。

Feb 28 to Mar 28 should be exactly 1 month.

2011 年 2 月 28 日到 2012 年 2 月 28 日应该正好是 1 年。

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

在此处查看有关月份和年份差异的更多讨论

See more discussion on the month and year diffs here

对月份和年份差异的更改是在 2.0.0 中进行的。从版本 2.9.0 开始 diff 还支持季度单位。

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

moment#valueOf 只是输出自 Unix Epoch 以来的毫秒数,就像 Date#valueOf 一样。

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

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

要从 Moment 获取 Unix 时间戳(自纪元以来的秒数),请使用 moment#unix

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

注意:ECMAScript 将此称为 "时间值"

Note: ECMAScript calls this a "Time Value"

Unix 时间戳(秒) 1.6.0+

moment().unix();

moment#unix 输出一个 Unix 时间戳(自 Unix 纪元以来的秒数)。

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

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

该值被取整到最接近的秒,并且不包括毫秒分量。

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

月份的天数 1.5.0+

moment().daysInMonth();

获取当月的天数。

Get the number of days in the current month.

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

作为 Javascript 日期 1.0.0+

moment().toDate();

要获取 Moment.js 封装的原生 Date 对象的副本,请使用 moment#toDate

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

这将返回 moment 使用的 Date 的副本,因此对该 Date 的任何更改都不会导致 moment 发生变化。如果要更改 moment Date,请参见 moment#manipulatemoment#set

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

moment#native 已被 moment#toDate 取代,并从 1.6.0 起已弃用。

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

作为数组 1.7.0+

moment().toArray();

这将返回一个数组,该数组反映了 new Date() 中的参数。

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

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

作为 JSON 2.0.0+

moment().toJSON();

将对象序列化为 JSON 时,如果有 Moment 对象,将表示为 ISO8601 字符串,调整为 UTC。

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"}'

相反,如果你想要一个反映 moment utcOffset() 的 ISO8601 字符串,那么你可以像这样修改 toJSON 函数:

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

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

这改变了如下行为:

This changes the behavior as follows:

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

作为 ISO 8601 字符串 2.1.0+

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

将字符串格式化为 ISO8601 标准。

Formats a string to the ISO8601 standard.

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

请注意,.toISOString() 返回 UTC 时间戳,即使相关 moment 处于本地模式。这样做是为了与原生 JavaScript Date .toISOString() 规范保持一致,如 ES2015 规范 中所述。从 2.20.0 版本开始,你可以调用 .toISOString(true) 来阻止 UTC 转换。

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

从版本 2.8.4 开始,出于性能原因,使用原生 Date.prototype.toISOString(如果可用)。

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

作为对象 2.10.5+

moment().toObject();

这将返回一个包含年、月、月中某日、小时、分钟、秒、毫秒的对象。

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

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

作为字符串 2.1.0+

moment().toString();

返回一个英语字符串,格式与 JS Date 的 .toString() 类似。

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

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

检查 2.16.0+

moment().inspect();

返回一个机器可读的字符串,可以对其进行评估以产生相同的 moment。由于名称的原因,它还用于 node 交互式 shell 中以显示对象。

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

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

注意:此函数主要用于调试,并非所有情况都得到精确处理。

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

是否之前 2.0.0+

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

检查一个 moment 是否在另一个 moment 之前。第一个参数将被解析为 moment,如果不是的话。

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

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

如果要将粒度限制为毫秒以外的单位,请将单位作为第二个参数传递。

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

由于第二个参数决定了精度,而不仅仅是要检查的单个值,因此使用日期将检查年、月和日。

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

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

moment#isAftermoment#isSame 一样,moment#isBefore 支持 moment#startOf 支持的任何时间单位。

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

year month week isoWeek day hour minute second

如果没有传递给 moment#isBefore,它将默认为当前时间。

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

注意:moment().isBefore() 具有未定义的行为,不应使用!如果代码运行得很快,初始创建的 moment 将与在 isBefore 中创建的 moment 相同以执行检查,因此结果将是 false。但是,如果代码运行速度较慢,则 isBefore 中创建的 moment 可能明显晚于 moment() 中创建的 moment,因此调用将返回 true

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

是否相同 2.0.0+

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

检查一个 moment 是否与另一个 moment 相同。第一个参数将被解析为 moment,如果不是的话。

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

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

如果要将粒度限制为毫秒以外的单位,请将其作为第二个参数传递。

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

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

当包含第二个参数时,它将匹配所有等于或大于的单位。传入 month 将检查 monthyear。传入 day 将检查 daymonthyear

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

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

moment#isAftermoment#isBefore 一样,moment#isSame 支持 moment#startOf 支持的任何时间单位。

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

year month week isoWeek day hour minute second

如果两个 moment 的时区不同,则使用第一个 moment 的时区进行比较。

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

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

注意:moment().isSame() 具有未定义的行为,不应使用!如果代码运行得很快,最初创建的 moment 将与在 isSame 中创建的 moment 相同以执行检查,因此结果将是 true。但是,如果代码运行速度较慢,则 isSame 中创建的 moment 可能明显晚于 moment() 中创建的 moment,因此调用将返回 false

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

是否之后 2.0.0+

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

检查一个 moment 是否在另一个 moment 之后。第一个参数将被解析为 moment,如果不是的话。

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

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

如果要将粒度限制为毫秒以外的单位,请将单位作为第二个参数传递。

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

由于第二个参数决定了精度,而不仅仅是要检查的单个值,因此使用日期将检查年、月和日。

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

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

moment#isSamemoment#isBefore 一样,moment#isAfter 支持 moment#startOf 支持的任何时间单位。

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

year month week isoWeek day hour minute second

如果没有传递给 moment#isAfter,它将默认为当前时间。

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

moment().isAfter(); // false

是否相同或之前 2.11.0+

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

检查一个 moment 是否在另一个 moment 之前或与另一个 moment 相同。第一个参数将被解析为 moment,如果不是的话。

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

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

如果要将粒度限制为毫秒以外的单位,请将单位作为第二个参数传递。

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

由于第二个参数决定了精度,而不仅仅是要检查的单个值,因此使用日期将检查年、月和日。

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

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

moment#isAftermoment#isSame 一样,moment#isSameOrBefore 支持 moment#startOf 支持的任何时间单位:

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

year month week isoWeek day hour minute second

是否相同或之后 2.11.0+

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

检查一个 moment 是否在另一个 moment 之后或与另一个 moment 相同。第一个参数将被解析为 moment,如果不是的话。

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

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

如果要将粒度限制为毫秒以外的单位,请将单位作为第二个参数传递。

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

由于第二个参数决定了精度,而不仅仅是要检查的单个值,因此使用日期将检查年、月和日。

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

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

moment#isSamemoment#isBefore 一样,moment#isSameOrAfter 支持 moment#startOf 支持的任何时间单位:

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

year month week isoWeek day hour minute second

是否之间 2.9.0+

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

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

检查某个 moment 是否位于其他两个 moment 之间,可以选择查看单位尺度(分钟、小时、天等)。匹配是排他性的。前两个参数将被解析为 moment,如果不是的话。

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

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

请注意,两个参数的顺序很重要:"更小的" 日期应该在第一个参数中。

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

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

如果要将粒度限制为毫秒以外的单位,请将单位作为第三个参数传递。

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

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

moment#isSamemoment#isBeforemoment#isAfter 一样,moment#startOf 支持的任何时间单位也支持 moment#isBetween。年、月、周、isoWeek、日、小时、分钟和秒。

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

2.13.0 版本引入了包容性。[ 表示包含一个值。( 表示排除。如果使用包容性参数,则必须传递两个指标。

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

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

请注意,如果 fromto 参数相同,但包含性参数不同,则为 false。

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

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

如果未指定包含性参数,Moment 将默认为 ()

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

是否夏令时 1.2.0+

moment().isDST();

moment#isDST 检查当前 moment 是否处于夏令时。

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

注意:这个函数是一个 HACK。moment 无法知道给定时间是否在实际 DST 中。区域中的某些时间更改与 DST 相关,有些则不相关,如果没有完整的时区信息,它就无法知道。

NOTE: This function is a HACK. moment has no way of knowing if a given time is in actual DST or not. Some time changes in a zone are DST related, some are not, and without complete timezone information it can't know.

Moment 当前检查冬季和夏季时间,如果偏移量与夏季偏移量匹配(夏季休假与冬季休假不同),则它会报告夏令时。这适用于绝大多数情况,但如上所述,不是 "correct" 并且不适用于所有情况。所以不要来找我们抗诉。

Moment currently checks the winter and summer time, and if the offset matches the summer offset (and summer off is different than winter off), then it reports DST. This works in vast majority of cases, but as mentioned above, is not "correct" and won't work for all cases. So don't come to us complaining.

活动 moment 时区(在编写 0.5.37 时)不支持 DST 信息(即时钟是否在给定 moment 正式在 DST 中),所以为了让事情变得更好一些新东西(和 tzdata 打包)有发生在 moment 时区。

Event moment-timezone (at moment of writing 0.5.37) doesn't support DST info (i.e is the clock officially in DST at a given moment or not), so for things to get better some new stuff (and tzdata bundling) has to happen in moment-timezone.

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

夏令时是否改变 开始于 2.3.0,弃用于 2.14.0

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

注意:从版本 2.14.0 开始,此函数已被弃用。修改 moment 对象后,它没有给出正确的答案。有关详细信息,请参阅 moment/3160

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

另一个重要的验证是了解日期是否已被 DST 移动。例如,在美国大部分地区:

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

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

这是因为夏令时将时间从 2:00 改为 3:00,因此 2:30 不是真实时间。结果时间取决于浏览器,可以向前或向后调整时间。使用 moment#isDSTShifted 测试此条件。

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.

注意:在 2.3.0 之前,这种情况下的 Moment 对象总是为 moment#isValid 返回 false;他们现在返回 true

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

是否闰年 1.0.0+

moment().isLeapYear();

如果该年是闰年,则 moment#isLeapYear 返回 true,否则返回 false

moment#isLeapYear returns true if that year is a leap year, and false if it is not.

moment([2000]).isLeapYear() // true
moment([2001]).isLeapYear() // false
moment([2100]).isLeapYear() // false

是否 Moment 1.5.0+

moment.isMoment(obj);

要检查变量是否为 moment 对象,请使用 moment.isMoment()

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

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

从 2.11.0 版本开始,你还可以通过 instanceof 操作符测试 moment 对象:

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

moment() instanceof moment // true

是否日期 2.9.0+

moment.isDate(obj);

要检查变量是否为原生 js Date 对象,请使用 moment.isDate()

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

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

Moment.js 对国际化有强大的支持。

Moment.js has robust support for internationalization.

你可以加载多个语言环境并在它们之间轻松切换。

You can load multiple locales and easily switch between them.

除了分配全局区域设置外,你还可以为特定 moment 分配区域设置。

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

全局地更改语言环境 1.0.0+

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

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

默认情况下,Moment.js 带有英语(美国)语言环境字符串。如果你需要其他语言环境,可以将它们加载到 Moment.js 中以备后用。

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

要加载语言环境,请将键和字符串值传递给 moment.locale

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

有关语言环境包每个部分的更多详细信息,请参见 定制 部分。

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

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

有关 week.dowweek.doy 的详细信息,请参阅 定制 部分。

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

加载语言环境后,它就会成为活动语言环境。要更改活动区域设置,只需使用已加载区域设置的键调用 moment.locale

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

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

从 2.21.0 开始,如果区域设置不可用,Moment 将会 console.warn

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

从 2.8.0 开始,更改全局区域设置不会影响现有实例。

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

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

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

moment.locale 返回使用的语言环境。这很有用,因为如果 Moment 不知道你指定的语言环境,它就不会更改语言环境。

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

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

你还可以指定区域列表,Moment 将使用第一个具有本地化的区域。

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

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

Moment 还将尝试从最具体到最不具体的区域设置说明符子字符串,直到找到它知道的区域设置。这在为 Moment 提供从用户环境中提取的语言环境字符串(例如 window.navigator.language)时很有用。

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

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

最后,Moment 将智能地搜索一组区域设置及其子字符串。

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

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

逻辑工作如下 - 选择下一个语言环境并按原样尝试。如果失败,代码通常会尝试删除最后一位(通常是国家名称)并重试。但是,如果下一个数组元素与要尝试的元素具有相同或更长的前缀,则迭代继续。因此,例如,如果数组具有序列

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

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

然后首先尝试 "AA-BB",然后一个天真的解决方案会尝试 "AA",但是这个解决方案会检查 "AA-CC" 实际上比 "AA" 更具体,所以它接下来会尝试 "AA-CC",只有在失败后(如果失败)它才会尝试 "AA", 因为 "XX-YY" 没有 "AA" 作为前缀。所以最后按此顺序尝试以下语言环境(假设全部失败,所以尝试下一个):

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

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

局部地更改语言环境 1.7.0+

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

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

在传递可能需要格式化为不同语言环境的 moment 时,全局语言环境配置可能会出现问题。

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

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

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

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

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

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

如果你不带参数调用 moment#locale,你将取回当时将使用的语言环境配置。

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

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

如果你需要暂时访问语言环境数据,这是首选的方式。

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

从 2.3.0 开始,你还可以指定区域设置标识符数组。它的工作方式与 全局语言环境配置 相同。

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

在 NodeJS 中加载语言环境 1.0.0+

moment.locale(String);

在 NodeJS 中加载语言环境非常容易。如果 moment/locale/ 中有以该键命名的语言环境文件,则先导入它,然后调用 moment.locale 加载它。

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

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

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

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

要省去加载单个语言环境的步骤(即只加载它们),改为导入 moment/min/moment-with-locales 模块。

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

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

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

如果你希望支持你的语言环境,请使用 所需的语言环境和单元测试文件 创建对 develop 分支的拉取请求。

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

在浏览器中加载语言环境 1.0.0+

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

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

在浏览器中加载语言环境只需要你包含语言环境文件。请务必指定字符集以防止编码问题。

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

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

所有语言环境都有缩小版本:

There are minified versions of all locales together:

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

为了最小化 HTTP 请求,使用我们的 Grunt 任务来编译带有自定义语言环境列表的 Moment

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

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

如果你使用 JSPM 作为插件管理器,你应该在你的库中添加语言环境。

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

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

注意:语言环境文件以 UMD 风格定义,因此它们应该可以在所有环境中无缝工作。

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

将你的语言环境添加到 Moment.js

要将你的语言环境添加到 Moment.js,请提交包含语言环境文件和测试文件的拉取请求。你可以在 moment/src/locale/fr.jsmoment/src/test/locale/fr.js 中找到示例。

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

要在 Node.js 中运行测试,请执行 npm install,然后执行 grunt

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.js 语言环境 1.6.0+

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

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

如果你经常更改语言环境,你可能想知道当前使用的是什么语言环境。这就像不带任何参数调用 moment.locale 一样简单。

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

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

从版本 2.12.0 开始,可以列出所有已加载且可供使用的语言环境:

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

moment.locales()

列出当前 Moment.js 语言环境的月份和星期 2.3.0+

moment.months()
moment.monthsShort()
moment.weekdays()
moment.weekdaysShort()
moment.weekdaysMin()

有时获取区域设置中的月份或星期列表很有用,例如在填充下拉菜单时。

It is sometimes useful to get the list of months or weekdays in a locale, for example when populating a dropdown menu.

moment.months();

返回当前语言环境中的月份列表。

Returns the list of months in the current locale.

[ 'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December' ]

同样,moment.monthsShort 返回缩写的月份名称,moment.weekdaysmoment.weekdaysShortmoment.weekdaysMin 返回星期列表。

Similarly, moment.monthsShort returns abbreviated month names, and moment.weekdays, moment.weekdaysShort, moment.weekdaysMin return lists of weekdays.

你可以将一个整数传递到每个函数中以获得特定的月份或星期。

You can pass an integer into each of those functions to get a specific month or weekday.

moment.weekdays(3); // 'Wednesday'

从 2.13.0 开始,你可以传递 bool 作为工作日函数的第一个参数。如果为 true,星期将以特定于语言环境的顺序返回。例如,在阿拉伯语环境中,星期六是一周的第一天,因此:

As of 2.13.0 you can pass a bool as the first parameter of the weekday functions. If true, the weekdays will be returned in locale specific order. For instance, in the Arabic locale, Saturday is the first day of the week, thus:

moment.locale('ar');
moment.weekdays(true); // lists weekdays Saturday-Friday in Arabic
moment.weekdays(true, 2); //will result in Monday in Arabic

注意:缺少特定于语言环境的参数,星期始终将星期日作为索引 0,而不管本地一周的第一天。

Note: Absent the locale specific parameter, weekdays always have Sunday as index 0, regardless of the local first day of the week.

某些语言环境在格式化月份名称时会进行特殊考虑。例如,荷兰语格式化没有尾随句点的月份缩写,但前提是它在破折号之间格式化月份。months 方法支持传递一种格式,以便月份将在适当的上下文中列出。

Some locales make special considerations into account when formatting month names. For example, Dutch formats month abbreviations without a trailing period, but only if it's formatting the month between dashes. The months method supports passing a format in so that the months will be listed in the proper context.

moment.locale('nl');
moment.monthsShort(); // ['jan.', 'feb.', 'mrt.', ...]
moment.monthsShort('-MMM-'); // [ 'jan', 'feb', 'mrt', ...]

最后,你可以结合使用格式选项和整数选项。

And finally, you can combine both the format option and the integer option.

moment.monthsShort('-MMM-', 3); // 'apr'

访问特定于语言环境的功能 2.8.0+

localeData = moment.localeData()
localeData.months(Moment)
localeData.months()
localeData.monthsShort(Moment)
localeData.monthsShort()
localeData.monthsParse(String)
localeData.weekdays(Moment)
localeData.weekdays()
localeData.weekdays(Boolean)      ## Added 2.24.0, sorts weekdays by locale
localeData.weekdaysShort(Moment)
localeData.weekdaysShort()
localeData.weekdaysShort(Boolean) ## Added 2.24.0, sorts weekdays by locale
localeData.weekdaysMin(Moment)
localeData.weekdaysMin()
localeData.weekdaysMin(Boolean)   ## Added 2.24.0, sorts weekdays by locale
localeData.weekdaysParse(String)
localeData.longDateFormat(String)
localeData.isPM(String)
localeData.meridiem(Number, Number, Boolean)
localeData.calendar(String, Moment)
localeData.relativeTime(Number, Boolean, String, Boolean)
localeData.pastFuture(Number, String)
localeData.ordinal(Number)
localeData.preparse(String)
localeData.postformat(String)
localeData.week(Moment)
localeData.invalidDate()
localeData.firstDayOfWeek()
localeData.firstDayOfYear()

你可以通过 moment.localeData(key) 函数访问当前加载的语言环境的属性。它返回当前语言环境或具有给定键的语言环境:

You can access the properties of the currently loaded locale through the moment.localeData(key) function. It returns the current locale or a locale with the given key:

// get current locale
var currentLocaleData = moment.localeData();
var frLocaleData = moment.localeData('fr');

返回的对象有以下方法:

The returned object has the following methods:

localeData.months(aMoment);  // full month name of aMoment
localeData.monthsShort(aMoment);  // short month name of aMoment
localeData.monthsParse(longOrShortMonthString);  // returns month id (0 to 11) of input
localeData.weekdays(aMoment);  // full weekday name of aMoment
localeData.weekdaysShort(aMoment);  // short weekday name of aMoment
localeData.weekdaysMin(aMoment);  // min weekday name of aMoment
localeData.weekdaysParse(minShortOrLongWeekdayString);  // returns weekday id (0 to 6) of input
localeData.longDateFormat(dateFormat);  // returns the full format of abbreviated date-time formats LT, L, LL and so on
localeData.isPM(amPmString);  // returns true iff amPmString represents PM
localeData.meridiem(hours, minutes, isLower);  // returns am/pm string for particular time-of-day in upper/lower case
localeData.calendar(key, aMoment);  // returns a format that would be used for calendar representation. Key is one of 'sameDay', 'nextDay', 'lastDay', 'nextWeek', 'prevWeek', 'sameElse'
localeData.relativeTime(number, withoutSuffix, key, isFuture);  // returns relative time string, key is on of 's', 'm', 'mm', 'h', 'hh', 'd', 'dd', 'M', 'MM', 'y', 'yy'. Single letter when number is 1.
localeData.pastFuture(diff, relTime);  // convert relTime string to past or future string depending on diff
localeData.ordinal(number);  // convert number to ordinal string 1 -> 1st
localeData.preparse(str);  // called before parsing on every input string
localeData.postformat(str);  // called after formatting on every string
localeData.week(aMoment);  // returns week-of-year of aMoment
localeData.invalidDate();  // returns a translation of 'Invalid date'
localeData.firstDayOfWeek();  // 0-6 (Sunday to Saturday)
localeData.firstDayOfYear();  // 0-15 Used to determine first week of the year.

有关 firstDayOfYear 的详细信息,请参阅 定制 部分。

Details about firstDayOfYear can be found in the customization section.

伪语言环境 2.13.0+

moment.locale('x-pseudo')

从版本 2.13.0 开始,moment 可以选择包含伪语言环境。此语言环境将使用非常明显更改的数据填充日期。伪语言环境在测试时很有用,因为它们可以清楚地表明哪些数据已本地化,哪些尚未本地化。只需包含伪语言环境,并将 moment 的语言环境设置为 x-pseudo。来自 Moment 的文本将很容易被发现。

As of version 2.13.0 moment optionally includes a pseudo locale. This locale will populate the dates with very obviously changed data. Pseudo locales can be useful when testing, as they make obvious what data has and has not been localized. Just include the pseudo-locale, and set moment's locale to x-pseudo. Text from Moment will be very easy to spot.

moment.locale('x-pseudo');
moment().format('LLL'); //14 F~ébrú~árý 2010 15:25
moment().fromNow(); //'á ~féw ~sécó~ñds á~gó'
moment().calendar(); //'T~ódá~ý át 02:00'

Moment.js 非常容易定制。通常,你应该使用你的自定义创建区域设置。

Moment.js is very easy to customize. In general, you should create a locale setting with your customizations.

moment.locale('en-my-settings', {
    // customizations.
});

你可以通过将 null 作为第二个参数传递来删除先前定义的语言环境。删除的语言环境将不再可用。

You can remove a previously defined locale by passing null as the second argument. The deleted locale will no longer be available for use.

moment.locale('fr'); // 'fr'
moment.locale('en'); // 'en'
moment.locale('fr', null);
moment.locale('fr'); // 'en'

从 2.12.0 开始,可以创建从父区域设置继承的区域设置。

As of 2.12.0 it is possible to create a locale that inherits from a parent locale.

moment.defineLocale('en-foo', {
  parentLocale: 'en',
  /* */
});

未在语言环境中指定的属性将从父语言环境继承。

Properties that are not specified in the locale will be inherited from the parent locale.

从 2.16.0 开始,可以使用父级定义语言环境,而该语言环境本身尚未定义或加载。

As of 2.16.0 it is possible to define a locale with a parent that hasn't itself been defined or loaded.

moment.defineLocale('fakeLocale', {parentLocale:'xyz'})

从 2.21.0 开始,当尝试使用新定义的语言环境创建 moment 时,moment 将尝试延迟加载父级(如果存在)。如果失败,它将默认父级为全局语言环境。

As of 2.21.0 when attempting to create a moment with the newly defined locale, moment will attempt to lazy load the parent if it exists. Failing that it will default the parent to the global locale.

从 2.12.0 开始,还可以更新区域设置的属性。

As of 2.12.0 it is also possible to update a locale's properties.

moment.updateLocale('en', {
  /**/
});

指定的任何属性都将更新,而其他属性将保持不变。此函数不会影响已经存在的 moment。请注意,调用 updateLocale 还会将当前的全局语言环境更改为已更新的语言环境;有关详细信息,请参阅 这个 GitHub 问题

Any properties specified will be updated, while others will remain the same. This function does not affect moments that already exist. Note that calling updateLocale also changes the current global locale, to the locale that is updated; see this GitHub issue for more information.

要恢复更新使用:

To revert an update use:

moment.updateLocale('en', null);

2.12.0 已弃用使用 moment.locale() 更改现有区域设置。请改用 moment.updateLocale()

2.12.0 deprecated using moment.locale() to change an existing locale. Use moment.updateLocale() instead.

月份名称 1.0.0+

// From 2.12.0 onward
moment.updateLocale('en', {
    months : String[]
});
moment.updateLocale('en', {
    months : Function
});
moment.updateLocale('en', {
    months : {
        format : String[],
        standalone : String[]
    }
});
// From 2.11.0
moment.locale('en', {
    months : {
        format : String[],
        standalone : String[]
    }
});
// From 2.8.1 to 2.11.2
moment.locale('en', {
    months : String[]
});
moment.locale('en', {
    months : Function
});

// Deprecated in 2.8.1
moment.lang('en', {
    months : String[]
});
moment.lang('en', {
    months : Function
});

Locale#months 应该是月份名称的数组。

Locale#months should be an array of the month names.

moment.updateLocale('en', {
    months : [
        "January", "February", "March", "April", "May", "June", "July",
        "August", "September", "October", "November", "December"
    ]
});

如果你需要更多的处理来计算月份的名称,(例如,如果不同的格式有不同的语法),Locale#months 可以是一个具有以下签名的函数。它应该总是返回一个月份名称。

If you need more processing to calculate the name of the month, (for example, if there is different grammar for different formats), Locale#months can be a function with the following signature. It should always return a month name.

moment.updateLocale('en', {
    months : function (momentToFormat, format) {
        // momentToFormat is the moment currently being formatted
        // format is the formatting string
        if (/^MMMM/.test(format)) { // if the format starts with 'MMMM'
            return nominative[momentToFormat.month()];
        } else {
            return subjective[momentToFormat.month()];
        }
    }
});

从版本 2.11.0 开始,月份也可以是一个对象,指定 standaloneformat 形式(主格和宾格)。在格式上运行以检查是否使用 format 形式的正则表达式是 /D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/。从版本 2.14.0 开始,可以使用 isFormat 键指定不同的键。

From version 2.11.0 months can also be an object, specifying standalone and format forms (nominative and accusative). The regular expression that is run on the format to check whether to use the format form is /D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/. From version 2.14.0 a different one can be specified with the isFormat key.

moment.updateLocale('en', {
    months : {
         format: 'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split('_'),
         standalone: 'sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis'.split('_'),
         isFormat: /D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?|MMMM?(\[[^\[\]]*\]|\s+)+D[oD]?/  // from 2.14.0
    }
});

月份缩写 1.0.0+

// From 2.12.0 onward
moment.updateLocale('en', {
    monthsShort : String[]
});
moment.updateLocale('en', {
    monthsShort : Function
});
moment.updateLocale('en', {
    monthsShort : {
        format: String[],
        standalone : String[]
    }
});
// From 2.11.0
moment.locale('en', {
    monthsShort : {
        format: String[],
        standalone : String[]
    }
});
// From 2.8.1 to 2.11.2
moment.locale('en', {
    monthsShort : String[]
});
moment.locale('en', {
    monthsShort : Function
});

// Deprecated in 2.8.1
moment.lang('en', {
    monthsShort : String[]
});
moment.lang('en', {
    monthsShort : Function
});

Locale#monthsShort 应该是月份缩写的数组。

Locale#monthsShort should be an array of the month abbreviations.

moment.updateLocale('en', {
    monthsShort : [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    ]
});

Locale#months 一样,Locale#monthsShort 也可以是回调函数。

Like Locale#months, Locale#monthsShort can be a callback function as well.

moment.updateLocale('en', {
    monthsShort : function (momentToFormat, format) {
        if (/^MMMM/.test(format)) {
            return nominative[momentToFormat.month()];
        } else {
            return subjective[momentToFormat.month()];
        }
    }
});

注意:从 2.11.0 版本开始,与 Locale#monthsLocale#monthsShort 一样,Locale#monthsShort 可以是具有 standaloneformat 情况的对象。

Note: From version 2.11.0, like Locale#months, Locale#monthsShort can be an object with standalone and format cases.

moment.updateLocale('en', {
    monthsShort : {
        format: 'янв_фев_мар_апр_мая_июня_июля_авг_сен_окт_ноя_дек'.split('_'),
        standalone: 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_')
    }
});

星期名称 1.0.0+

// From version 2.12.0 onward
moment.updateLocale('en', {
    weekdays : String[]
});
moment.updateLocale('en', {
    weekdays : Function
});
moment.updateLocale('en', {
    weekdays : {
        standalone : String[],
        format : String[],
        isFormat : RegExp
    }
});
// From version 2.11.0
moment.locale('en', {
    weekdays : {
        standalone : String[],
        format : String[],
        isFormat : Boolean
    }
});
// From version 2.8.1 to 2.11.2
moment.locale('en', {
    weekdays : String[]
});
moment.locale('en', {
    weekdays : Function
});

// Deprecated version 2.8.1
moment.lang('en', {
    weekdays : String[]
});
moment.lang('en', {
    weekdays : Function
});

Locale#weekdays 应该是星期名称的数组。

Locale#weekdays should be an array of the weekdays names.

moment.updateLocale('en', {
    weekdays : [
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ]
});

Locale#weekdays 也可以是回调函数。

Locale#weekdays can be a callback function as well.

moment.updateLocale('en', {
    weekdays : function (momentToFormat, format) {
        return weekdays[momentToFormat.day()];
    }
});

注意:从版本 2.11.0 开始,格式/独立案例也可以通过。isFormat 将根据完整格式字符串来确定要使用的格式。

Note: From version 2.11.0 format/standalone cases can be passed as well. isFormat will be used against the full format string to determine which form to use.

moment.updateLocale('en', {
    weekdays : {
        standalone: 'Воскресенье_Понедельник_Вторник_Среда_Четверг_Пятница_Суббота'.split('_'),
        format: 'Воскресенье_Понедельник_Вторник_Среду_Четверг_Пятницу_Субботу'.split('_'),
        isFormat: /\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/
    }
});

星期缩写 1.0.0+

// From 2.12.0 onward
moment.updateLocale('en', {
    weekdaysShort : String[]
});
moment.updateLocale('en', {
    weekdaysShort : Function
});
// From 2.8.1 to 2.11.2
moment.locale('en', {
    weekdaysShort : String[]
});
moment.locale('en', {
    weekdaysShort : Function
});

// Deprecated in 2.8.1
moment.lang('en', {
    weekdaysShort : String[]
});
moment.lang('en', {
    weekdaysShort : Function
});

Locale#weekdaysShort 应该是星期缩写的数组。

Locale#weekdaysShort should be an array of the weekdays abbreviations.

moment.updateLocale('en', {
    weekdaysShort : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
});

Locale#weekdaysShort 也可以是回调函数。

Locale#weekdaysShort can be a callback function as well.

moment.updateLocale('en', {
    weekdaysShort : function (momentToFormat, format) {
        return weekdaysShort[momentToFormat.day()];
    }
});

最小星期缩写 1.7.0+

// From 2.12.0 onward
moment.updateLocale('en', {
    weekdaysMin : String[]
});
moment.updateLocale('en', {
    weekdaysMin : Function
});

// From 2.8.1 to 2.11.2
moment.locale('en', {
    weekdaysMin : String[]
});
moment.locale('en', {
    weekdaysMin : Function
});

// Deprecated in 2.8.1
moment.lang('en', {
    weekdaysMin : String[]
});
moment.lang('en', {
    weekdaysMin : Function
});

Locale#weekdaysMin 应该是两个字母星期缩写的数组。这些的目的是用于日历选择器之类的东西,因此它们应该尽可能小。

Locale#weekdaysMin should be an array of two letter weekday abbreviations. The purpose of these is for things like calendar pickers, thus they should be as small as possible.

moment.updateLocale('en', {
    weekdaysMin : ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
});

Locale#weekdaysMin 也可以是回调函数。

Locale#weekdaysMin can be a callback function as well.

moment.updateLocale('en', {
    weekdaysMin : function (momentToFormat, format) {
        return weekdaysMin[momentToFormat.day()];
    }
});

长日期格式 1.1.0+

// From 2.12.0 onward
moment.updateLocale('en', {
    weekdaysMin : String[]
});
moment.updateLocale('en', {
    weekdaysMin : Function
});

// From 2.8.1 to 2.11.2
moment.locale('en', {
    longDateFormat : Object
});

// Deprecated in 2.8.1
moment.lang('en', {
    longDateFormat : Object
});

Locale#longDateFormat 应该是一个包含每个长日期格式 L LL LLL LLLL LT LTS 的键/值对的对象。LT 应该是时间格式,也用于 moment#calendar

Locale#longDateFormat should be an object containing a key/value pair for each long date format L LL LLL LLLL LT LTS. LT should be the time format, and is also used for moment#calendar.

moment.updateLocale('en', {
    longDateFormat : {
        LT: "h:mm A",
        LTS: "h:mm:ss A",
        L: "MM/DD/YYYY",
        l: "M/D/YYYY",
        LL: "MMMM Do YYYY",
        ll: "MMM D YYYY",
        LLL: "MMMM Do YYYY LT",
        lll: "MMM D YYYY LT",
        LLLL: "dddd, MMMM Do YYYY LT",
        llll: "ddd, MMM D YYYY LT"
    }
});

你可以消除小写的 l 标记,它们将通过用短标记变体替换长标记来自动创建。

You can eliminate the lowercase l tokens and they will be created automatically by replacing long tokens with the short token variants.

moment.updateLocale('en', {
    longDateFormat : {
        LT: "h:mm A",
        LTS: "h:mm:ss A",
        L: "MM/DD/YYYY",
        LL: "MMMM Do YYYY",
        LLL: "MMMM Do YYYY LT",
        LLLL: "dddd, MMMM Do YYYY LT"
    }
});

相对时间 1.0.0+

// From 2.12.0 onward
moment.updateLocale('en', {
    relativeTime : Object
});
// From 2.8.1 to 2.11.2
moment.locale('en', {
    relativeTime : Object
});

// Deprecated in 2.8.1
moment.lang('en', {
    relativeTime : Object
});

Locale#relativeTime 应该是 moment#from 的替换字符串的对象。

Locale#relativeTime should be an object of the replacement strings for moment#from.

moment.updateLocale('en', {
    relativeTime : {
        future: "in %s",
        past:   "%s ago",
        s  : 'a few seconds',
        ss : '%d seconds',
        m:  "a minute",
        mm: "%d minutes",
        h:  "an hour",
        hh: "%d hours",
        d:  "a day",
        dd: "%d days",
        w:  "a week",
        ww: "%d weeks",
        M:  "a month",
        MM: "%d months",
        y:  "a year",
        yy: "%d years"
    }
});

Locale#relativeTime.future 指未来日期的前缀/后缀,Locale#relativeTime.past 指过去日期的前缀/后缀。对于所有其他字符,单字符表示单数,双字符表示复数。

Locale#relativeTime.future refers to the prefix/suffix for future dates, and Locale#relativeTime.past refers to the prefix/suffix for past dates. For all others, a single character refers to the singular, and a double character refers to the plural.

如果语言环境需要对令牌进行额外处理,它可以将令牌设置为具有以下签名的函数。该函数应返回一个字符串。

If a locale requires additional processing for a token, it can set the token as a function with the following signature. The function should return a string.

function (number, withoutSuffix, key, isFuture) {
    return string;
}

key 参数引用 Locale#relativeTime 对象中的替换键。(例如 s m mm h 等)

The key argument refers to the replacement key in the Locale#relativeTime object. (eg. s m mm h, etc.)

number 参数指的是该键的单位数。对于 m,数字是分钟数等。

The number argument refers to the number of units for that key. For m, the number is the number of minutes, etc.

如果令牌不带后缀显示,则 withoutSuffix 参数将为 true,如果带后缀显示,则为 false。(倒置逻辑的原因是因为默认行为是用后缀显示。)

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

如果要使用未来的后缀/前缀,则 isFuture 参数将为真;如果要使用过去的前缀/后缀,则为假。

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.

注意:2.25.0 中添加了对 www 的处理。

Note: Handling for w and ww was added in 2.25.0.

AM/PM 1.6.0+

// From 2.12.0 onward
moment.updateLocale('en', {
    meridiem : Function
});
// From 2.8.1 to 2.11.2
moment.locale('en', {
    meridiem : Function
});

// Deprecated in 2.8.1
moment.lang('en', {
    meridiem : Function
});

如果你的语言环境使用 'am/pm',则可以省略 Locale#meridiem,因为这些值是默认值。

If your locale uses 'am/pm', Locale#meridiem can be omitted, as those values are the defaults.

如果你的语言环境需要对 am/pm 进行任何不同的计算,Locale#meridiem 应该是一个回调函数,它根据小时、分钟和大写/小写返回正确的字符串。

If your locale needs any different computation for am/pm, Locale#meridiem should be a callback function that returns the correct string based on hour, minute, and upper/lowercase.

moment.updateLocale('zh-cn', {
    meridiem : function (hour, minute, isLowercase) {
        if (hour < 9) {
            return "早上";
        } else if (hour < 11 && minute < 30) {
            return "上午";
        } else if (hour < 13 && minute < 30) {
            return "中午";
        } else if (hour < 18) {
            return "下午";
        } else {
            return "晚上";
        }
    }
});

AM/PM 解析 2.1.0+

// From 2.12.0 onward
moment.updateLocale('en', {
    meridiemParse : RegExp
    isPM : Function
});

// From 2.8.1 to 2.11.2
moment.locale('en', {
    meridiemParse : RegExp
    isPM : Function
});

// Deprecated in 2.8.1
moment.lang('en', {
    meridiemParse : RegExp
    isPM : Function
});

如果输入字符串超过中午 12 点,Locale#isPM 应返回真。这用于解析 a A 令牌。

Locale#isPM should return true if the input string is past 12 noon. This is used in parsing the a A tokens.

moment.updateLocale('en', {
    isPM : function (input) {
        return ((input + '').toLowerCase()[0] === 'p');
    }
});

要配置应将哪些字符串解析为输入,请设置 meridiemParse 属性。

To configure what strings should be parsed as input, set the meridiemParse property.

moment.updateLocale('en', {
    meridiemParse : /[ap]\.?m?\.?/i
});

日历 1.3.0+

// From 2.12.0 onward
moment.updateLocale('en', {
    calendar : Object
});
// From 2.8.1 to 2.11.2
moment.locale('en', {
    calendar : Object
});

// Deprecated in 2.8.1
moment.lang('en', {
    calendar : Object
});

Locale#calendar 应具有以下格式字符串。

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'
    }
});

每个 Locale#calendar 键也可以是一个回调函数,其范围是当前 moment,第一个参数是描述现在的 moment。它应该返回一个格式化字符串。

Each of the Locale#calendar keys can also be a callback function with the scope of the current moment and first argument a moment that depicts now. It should return a formatting string.

function callback (now) {
    return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
}

日历格式 2.14.0+

moment.calendarFormat = Function

这使你可以修改 日历 使用的标记。

This lets you modify the tokens used by calendar.

moment.calendarFormat = function (myMoment, now) {
    var diff = myMoment.diff(now, 'days', true);
    var nextMonth = now.clone().add(1, 'month');

    var retVal =  diff < -6 ? 'sameElse' :
        diff < -1 ? 'lastWeek' :
        diff < 0 ? 'lastDay' :
        diff < 1 ? 'sameDay' :
        diff < 2 ? 'nextDay' :
        diff < 7 ? 'nextWeek' :
        // introduce thisMonth and nextMonth
        (myMoment.month() === now.month() && myMoment.year() === now.year()) ? 'thisMonth' :
        (nextMonth.month() === myMoment.month() && nextMonth.year() === myMoment.year()) ? 'nextMonth' : 'sameElse';
    return retVal;
};

序数 1.0.0+

// From 2.12.0 onward
moment.updateLocale('en', {
    ordinal : Function
});
// From 2.8.1 to 2.11.2
moment.locale('en', {
    ordinal : Function
});

// Deprecated in 2.8.1
moment.lang('en', {
    ordinal : Function
});

Locale#ordinal 应该是一个返回给定数字序数的函数。

Locale#ordinal should be a function that returns the ordinal for a given number.

moment.updateLocale('en', {
    ordinal : function (number, token) {
        var b = number % 10;
        var output = (~~ (number % 100 / 10) === 1) ? 'th' :
            (b === 1) ? 'st' :
            (b === 2) ? 'nd' :
            (b === 3) ? 'rd' : 'th';
        return number + output;
    }
});

从 2.0.0 开始,序数函数应返回数字和序数。以前,只返回序号。

As of 2.0.0, the ordinal function should return both the number and the ordinal. Previously, only the ordinal was returned.

从 2.1.0 开始,添加了 token 参数。它是正在被排序的令牌字符串,例如:Md

As of 2.1.0, the token parameter was added. It is a string of the token that is being ordinalized, for example: M or d.

有关序号的更多信息,请参阅 维基百科

For more information on ordinal numbers, see Wikipedia.

相对时间阈值 2.7.0+

moment.relativeTimeThreshold(unit);  // getter
moment.relativeTimeThreshold(unit, limit);  // setter

duration.humanize 具有定义单位何时被视为一分钟、一小时等的阈值。例如,默认情况下超过 45 秒被视为一分钟,超过 22 小时被视为一天等等。要更改这些截止值,请使用 moment.relativeTimeThreshold(unit, limit),其中单位是 sssmhdwM 之一。

duration.humanize has thresholds which define when a unit is considered a minute, an hour and so on. For example, by default more than 45 seconds is considered a minute, more than 22 hours is considered a day and so on. To change those cutoffs use moment.relativeTimeThreshold(unit, limit) where unit is one of ss, s, m, h, d, w, M.

单位 意义 用法
ss 几秒 以秒为单位计算的最少秒数减 1。必须在设置 `s` 单位后或不设置 `s` 单位时进行设置。
s 秒数 被认为是一分钟的最少秒数。
m 分钟数 被认为是一个小时的最少分钟数。
h 小时数 被视为一天的最少小时数。
d 天数 被认为是一周的最少天数。
w 周数 最少要考虑一个月的周数。默认不使用。
M 月数 被认为一年的最少月数。
  // Retrieve existing thresholds
  moment.relativeTimeThreshold('ss'); // 44
  moment.relativeTimeThreshold('s');  // 45
  moment.relativeTimeThreshold('m');  // 45
  moment.relativeTimeThreshold('h');  // 22
  moment.relativeTimeThreshold('d');  // 26
  moment.relativeTimeThreshold('w');  // null (disabled)
  moment.relativeTimeThreshold('M');  // 11

  // Set new thresholds
  moment.relativeTimeThreshold('s', 40);
  moment.relativeTimeThreshold('ss', 3);
  moment.relativeTimeThreshold('m', 40);
  moment.relativeTimeThreshold('h', 20);
  moment.relativeTimeThreshold('d', 25);
  moment.relativeTimeThreshold('w', 4);  // enables weeks
  moment.relativeTimeThreshold('M', 10);

注意:2.25.0 中添加了周单位。默认情况下不使用它(设置为 null),但你可以将其设置为非空值,并且(可选)将 d 设置得更低,以便它从几天前过渡到几周前。

Note: Week unit was added in 2.25.0. By default it is not used (set to null), but you can set it to non-null value, and also (optionally) set d lower, so it transitions from days to weeks earlier.

注意:2.8.1 中添加了检索阈值。

Note: Retrieving thresholds was added in 2.8.1.

注意:2.18.0 中添加了检索和设置 ss 阈值。

Note: Retrieving and setting ss threshold was added in 2.18.0.

相对时间舍入 2.14.0+

moment.relativeTimeRounding();  // getter
moment.relativeTimeRounding(fn);  // setter

duration.humanize 在将其提供给语言环境中指定的 relativeTime 格式字符串之前舍入可能为双精度的值。要控制舍入,你可以使用 moment.relativeTimeRounding

duration.humanize rounds a possibly double value before supplying it to the relativeTime format string specified in the locale. To control the rounding you can use moment.relativeTimeRounding.

var roundingDefault = moment.relativeTimeRounding();

// Round relative time evaluation down
moment.relativeTimeRounding(Math.floor);

moment.relativeTimeThreshold('s', 60);
moment.relativeTimeThreshold('m', 60);
moment.relativeTimeThreshold('h', 24);
moment.relativeTimeThreshold('d', 7);
moment.relativeTimeThreshold('w', 4);
moment.relativeTimeThreshold('M', 12);

var a = moment();
a.subtract({hours: 23, minutes: 59, seconds: 59});
a.toNow();  // == 'in 23 hours'  'Round down towards the nearest hour'

// back to default
moment.relativeTimeRounding(roundingDefault);

你甚至可以选择完全不进行舍入:

You can even choose to do no rounding at all:

var retainValue = function (value) {
    return value;
};
moment.relativeTimeRounding(retainValue);

var a = moment();
a.subtract({hours: 39});
a.toNow(); // == 'in 1.625 days', 'Round down towards the nearest year'

更改时间源 2.11.0+

moment.now = function () { return +new Date(); }

如果你想更改 Moment 看到的时间,你可以指定一个返回自 Unix 纪元(1970 年 1 月 1 日)以来的毫秒数的方法。

If you want to change the time that Moment sees, you can specify a method that returns the number of milliseconds since the Unix epoch (January 1, 1970).

默认值是:

The default is:

moment.now = function () {
    return +new Date();
}

这将在调用 moment() 时使用,而当从 format() 中省略标记时将使用当前日期。通常,任何需要当前时间的方法都在底层使用它。

This will be used when calling moment(), and the current date used when tokens are omitted from format(). In general, any method that needs the current time uses this under the hood.

周的第一天和年的第一周 1.0.0+

// From 2.12.0 onward
moment.updateLocale('en', {
    week : {
        dow : Int,
        doy : Int
     }
});
// From 2.8.1 to 2.11.2
moment.locale('en', {
    week : {
        dow : Int,
        doy : Int
    }
});

// Deprecated in 2.8.1
moment.lang('en', {
    week : {
        dow : Int,
        doy : Int
    }
});

Locale#week.dow 应该是一个整数,代表一周的第一天,0 是星期日,1 是星期一,...,6 是星期六。

Locale#week.dow should be an integer representing the first day of the week, 0 is Sunday, 1 is Monday, ..., 6 is Saturday.

Locale#week.doy 应该是一个整数。doydow 一起使用来确定一年中的第一周。doy 计算为 7 + dow - janX,其中 janX 是一月的第一天,必须属于一年的第一周。

Locale#week.doy should be an integer. doy is used together with dow to determine the first week of the year. doy is calculated as 7 + dow - janX, where janX is the first day of January that must belong to the first week of the year.

// ISO-8601, Europe
moment.updateLocale("en", { week: {
  dow: 1, // First day of week is Monday
  doy: 4  // First week of year must contain 4 January (7 + 1 - 4)
}});

// US, Canada
moment.updateLocale("en", { week: {
  dow: 0, // First day of week is Sunday
  doy: 6  // First week of year must contain 1 January (7 + 0 - 1)
}});

// Many Arab countries
moment.updateLocale("en", { week: {
  dow: 6, // First day of week is Saturday
  doy: 12 // First week of year must contain 1 January (7 + 6 - 1)
}});

// Also common
moment.updateLocale("en", { week: {
  dow: 1, // First day of week is Monday
  doy: 7  // First week of year must contain 1 January (7 + 1 - 1)
}});

纪元 2.25.0+

moment.updateLocale('en', {
    eras: [{
        since:  '0001-01-01',
        until:  +Infinity,
        offset: 1,
        name:   'Anno Domini',
        narrow: 'AD',
        abbr:   'AD'
    }, {
        until:   -Infinity,
        since:  '0000-12-31',
        offset: 1,
        name:   'Before Christ',
        narrow: 'BC',
        abbr:   'BC'
    }],
});

为特定语言环境指定纪元。纪元是带有名称和年份编号的时间间隔。绝对年份数(如 2020)也可以指定为 2020 AD:公元 2020 年。同样,绝对年份数 -0500 可以描述为 501 BC,即公元前 501 年。

Specify Eras for a particular locale. An era is a time interval with name and year numbering. Absolute year number (like 2020) can also be specified as 2020 AD: the 2020th year of the era AD. Similarly the absolute year number -0500 can be described as 501 BC, the 501st year from the BC era.

eras: [{
    since:  '0001-01-01', // the start of the era
    until:  +Infinity,    // the end of the era, can be +/-Infinity
    offset: 1,            // added to year to (mostly) avoid 0 era years
    name:   'Anno Domini',// full name of era
    narrow: 'AD',         // narrow name of era
    abbr:   'AD'          // abbreviated name of era
}]

sinceuntil 支配着纪元的方向。与 BC 的情况一样,它向 -Infinity 生长,因此 since > until。对于向 +Infinity since < until 递增的时代。

since and until govern the direction of the era. As in the case of BC it grows toward -Infinity, thus since > until. For eras that increment toward +Infinity since < until.

纪元的解析/格式化是使用 yoy*N* 标记完成的。

Parsing/formatting of eras is accomplished with yo, y* and N* tokens.

注意:与纪元相关的 API 可能会发生变化。

Note: The era-related APIs are subject to change.

无效日期 2.3.0+

// From 2.12.0 onward
moment.updateLocale('en', {
    invalidDate : String
});

// From 2.8.1 to 2.11.2
moment.locale('en', {
    invalidDate : String
});

// Deprecated in 2.8.1
moment.lang('en', {
    invalidDate : String
});

Locale#invalidDate 应该是一个字符串。

Locale#invalidDate should be a string.

moment.updateLocale("es", {
  invalidDate: "Fecha invalida"
});

Moment.js 也有持续时间对象。当 moment 定义为单个时间点,持续时间定义为时间长度。

Moment.js also has duration objects. Where a moment is defined as a single point in time, a duration is defined as a length of time.

持续时间没有定义的开始和结束日期。它们是无上下文的。

Durations do not have a defined beginning and end date. They are contextless.

持续时间在概念上更类似于 '2 个小时' 而不是 '今天下午 2 点至 4 点之间'。因此,它们不是在依赖上下文的单位之间进行转换的好解决方案。

A duration is conceptually more similar to '2 hours' than to 'between 2 and 4 pm today'. As such, they are not a good solution to converting between units that depend on context.

例如,一年可以定义为 366 天、365 天、365.25 天、12 个月或 52 周。没有上下文,试图将年转换为天是没有意义的。与使用 Durations 相比,使用 moment#diff 计算两个 moment 之间的天数或年数要好得多。

For example, a year can be defined as 366 days, 365 days, 365.25 days, 12 months, or 52 weeks. Trying to convert years to days makes no sense without context. It is much better to use moment#diff for calculating days or years between two moments than to use Durations.

作为 在这里讨论,Moment.js 的持续时间格式与 ISO 8601 标称持续时间和 RFC 5545 持续时间的规范略有不同。

As discussed here, the duration format for Moment.js differs very slightly from the specifications for ISO 8601 nominal duration and RFC 5545 duration.

创建 1.6.0+

moment.duration(Number, String);
moment.duration(Number);
moment.duration(Object);
moment.duration(String);
moment.duration(String, String); // 2.25.0

要创建持续时间,请使用以毫秒为单位的时间长度调用 moment.duration()

To create a duration, call moment.duration() with the length of time in milliseconds.

moment.duration(100); // 100 milliseconds

如果你想创建一个非毫秒度量单位的 moment,你也可以传递度量单位。

If you want to create a moment with a unit of measurement other than milliseconds, you can pass the unit of measurement as well.

moment.duration(2, 'seconds');
moment.duration(2, 'minutes');
moment.duration(2, 'hours');
moment.duration(2, 'days');
moment.duration(2, 'weeks');
moment.duration(2, 'months');
moment.duration(2, 'years');
moment.duration('2', 'years'); // from 2.25.0

moment#addmoment#subtract 的相同简写在这里也适用。

The same shorthand for moment#add and moment#subtract works here as well.

速记
年数 y
月数 M
周数 w
天数 d
小时数 h
分钟数 m
秒数 s
毫秒数 ms

moment#add 非常相似,如果你需要多个不同的度量单位,则可以传递一个值对象。

Much like moment#add, you can pass an object of values if you need multiple different units of measurement.

moment.duration({
    seconds: 2,
    minutes: 2,
    hours: 2,
    days: 2,
    weeks: 2,
    months: '2',
    years: '2'
});

从 2.1.0 开始,moment 支持解析 ASP.NET 样式的时间跨度。支持以下格式。

As of 2.1.0, moment supports parsing ASP.NET style time spans. The following formats are supported.

格式是由冒号分隔的时、分、秒字符串,如 23:59:59。天数可以使用点分隔符作为前缀,例如 7.23:59:5923:59:59.999 也支持部分秒。

The format is an hour, minute, second string separated by colons like 23:59:59. The number of days can be prefixed with a dot separator like so 7.23:59:59. Partial seconds are supported as well 23:59:59.999.

moment.duration('23:59:59');
moment.duration('23:59:59.999');
moment.duration('7.23:59:59.999');
moment.duration('23:59'); // added in 2.3.0

从 2.3.0 开始,moment 还支持解析 ISO 8601 持续时间。

As of 2.3.0, moment also supports parsing ISO 8601 durations.

moment.duration('P1Y2M3DT4H5M6S');
moment.duration('P1M');

从 2.11.0 开始,支持天数和剩余时间之间有空格的持续时间格式字符串。

As of 2.11.0, duration format strings with a space between days and rest is supported.

moment.duration('7 23:59:59.999');

从 2.13.0 开始,解析持续时间时支持混合负号和正号。

As of 2.13.0, mixed negative and positive signs are supported when parsing durations.

moment.duration('PT-6H3M')

从 2.18.0 开始,支持无效持续时间,与无效 moment 类似。要创建无效的持续时间,你可以传递 NaN 作为单位值。

As of 2.18.0, invalid durations are supported, similarly to invalid moments. To create an invalid duration you can pass NaN for a value of a unit.

在即将发布的版本中,预计无效持续时间将涵盖更多情况(例如单位的空值)。

In upcoming releases expect invalid durations to cover more cases (like null values for units).

moment.duration(NaN);
moment.duration(NaN, 'days');
moment.duration.invalid();

克隆 2.19.0+

moment.duration().clone();

创建持续时间的克隆。持续时间是可变的,就像 moment 对象一样,所以这可以让你在某个时间点获得快照。

Create a clone of a duration. Durations are mutable, just like moment objects, so this lets you get a snapshot, at some point in time.

var d1 = moment.duration();
var d2 = d1.clone();
d1.add(1, 'second');
d1.asMilliseconds() !== d2.asMilliseconds();

人性化 1.6.0+

moment.duration().humanize();
moment.duration().humanize(withSuffix);
moment.duration().humanize(withSuffix, thresholds); // from 2.25.0
moment.duration().humanize(thresholds);             // from 2.25.0

有时候,你想要 moment#from 的所有优点,但你不想创造两个 moment,你只想显示一个时间长度。

Sometimes, you want all the goodness of moment#from but you don't want to have to create two moments, you just want to display a length of time.

输入 moment.duration().humanize()

Enter moment.duration().humanize().

moment.duration(1, "minutes").humanize(); // a minute
moment.duration(2, "minutes").humanize(); // 2 minutes
moment.duration(24, "hours").humanize();  // a day

默认情况下,返回字符串描述持续时间 a month(无后缀)。如果你想要定向持续时间 in a montha month ago(带后缀),请传入 true,如下所示。

By default, the return string is describing a duration a month (suffix-less). If you want an oriented duration in a month, a month ago (with suffix), pass in true as seen below.

moment.duration(1, "minutes").humanize(true); // in a minute

对于现在之前的后缀,传入一个负数。

For suffixes before now, pass in a negative number.

moment.duration(-1, "minutes").humanize(true); // a minute ago

无效的持续时间被人性化为 Invalid Date 的本地化版本。

Invalid durations are humanized to the localized version of Invalid Date.

moment.duration.invalid().humanize(); // Invalid Date

可以使用相对时间阈值配置人性化输出。要为特定的人性化调用指定阈值,请将它们作为唯一参数或在后缀 arg 之后传递:

Humanize output can be configured with relative time thresholds. To specify thresholds for a particular invocation of humanize, pass them as a sole argument or after suffix arg:

moment.duration(-1, 'week').humanize(true, {d: 7, w: 4}); // a week ago
moment.duration(-1, 'week').humanize({d: 7, w: 4}); // a week

注意:2.25.0 中添加了 Humanize 中的通过阈值。

Note: Passing thresholds in humanize was added in 2.25.0.

毫秒数 1.6.0+

moment.duration().milliseconds();
moment.duration().asMilliseconds();

要获取持续时间的毫秒数,请使用 moment.duration().milliseconds()

To get the number of milliseconds in a duration, use moment.duration().milliseconds().

它将返回 0 到 999 之间的数字。

It will return a number between 0 and 999.

moment.duration(500).milliseconds(); // 500
moment.duration(1500).milliseconds(); // 500
moment.duration(15000).milliseconds(); // 0

如果你想要持续时间的长度(以毫秒为单位),请改用 moment.duration().asMilliseconds()

If you want the length of the duration in milliseconds, use moment.duration().asMilliseconds() instead.

moment.duration(500).asMilliseconds(); // 500
moment.duration(1500).asMilliseconds(); // 1500
moment.duration(15000).asMilliseconds(); // 15000

秒数 1.6.0+

moment.duration().seconds();
moment.duration().asSeconds();

要获取持续时间中的秒数,请使用 moment.duration().seconds()

To get the number of seconds in a duration, use moment.duration().seconds().

它将返回 0 到 59 之间的数字。

It will return a number between 0 and 59.

moment.duration(500).seconds(); // 0
moment.duration(1500).seconds(); // 1
moment.duration(15000).seconds(); // 15

如果你想要持续时间的长度(以秒为单位),请改用 moment.duration().asSeconds()

If you want the length of the duration in seconds, use moment.duration().asSeconds() instead.

moment.duration(500).asSeconds(); // 0.5
moment.duration(1500).asSeconds(); // 1.5
moment.duration(15000).asSeconds(); // 15

分钟数 1.6.0+

moment.duration().minutes();
moment.duration().asMinutes();

与其他获取持续时间的方法一样,moment.duration().minutes() 获取分钟(0 - 59).

As with the other getters for durations, moment.duration().minutes() gets the minutes (0 - 59).

moment.duration().asMinutes() 获取持续时间的长度(以分钟为单位)。

moment.duration().asMinutes() gets the length of the duration in minutes.

小时数 1.6.0+

moment.duration().hours();
moment.duration().asHours();

与其他获取持续时间的方法一样,moment.duration().hours() 获取小时数 (0 - 23).

As with the other getters for durations, moment.duration().hours() gets the hours (0 - 23).

moment.duration().asHours() 获取持续时间的长度(以小时为单位)。

moment.duration().asHours() gets the length of the duration in hours.

天数 1.6.0+

moment.duration().days();
moment.duration().asDays();

与其他获取持续时间的方法一样,moment.duration().days() 获取天数 (0 - 30).

As with the other getters for durations, moment.duration().days() gets the days (0 - 30).

moment.duration().asDays() 获取以天为单位的持续时间长度。

moment.duration().asDays() gets the length of the duration in days.

周数 1.6.0+

moment.duration().weeks();
moment.duration().asWeeks();

与其他获取持续时间的方法一样,moment.duration().weeks() 获取周数 (0 - 4).

As with the other getters for durations, moment.duration().weeks() gets the weeks (0 - 4).

moment.duration().asWeeks() 获取持续时间的长度(以周为单位)。

moment.duration().asWeeks() gets the length of the duration in weeks.

请注意,与持续时间的其他获取器不同,周被算作天数的子集,并且不会从天数中扣除。

Pay attention that unlike the other getters for duration, weeks are counted as a subset of the days, and are not taken off the days count.

注意:以周为单位的持续时间长度定义为 7 天。

Note: The length of a duration in weeks is defined as 7 days.

月数 1.6.0+

moment.duration().months();
moment.duration().asMonths();

与其他获取持续时间的 getter 一样,moment.duration().months() 获取月份 (0 - 11).

As with the other getters for durations, moment.duration().months() gets the months (0 - 11).

moment.duration().asMonths() 获取持续时间的长度(以月为单位)。

moment.duration().asMonths() gets the length of the duration in months.

年数 1.6.0+

moment.duration().years();
moment.duration().asYears();

与持续时间的其他获取器一样,moment.duration().years() 获取年份。

As with the other getters for durations, moment.duration().years() gets the years.

moment.duration().asYears() 获取持续时间的长度(以年为单位)。

moment.duration().asYears() gets the length of the duration in years.

增加时间 2.1.0+

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

通过添加时间来改变原始持续时间。

Mutates the original duration by adding time.

用于创建持续时间的相同键和简写在这里可以用作第二个参数。

The same keys and shorthands used to create durations can be used here as the second argument.

var a = moment.duration(1, 'd');
var b = moment.duration(2, 'd');
a.add(b).days(); // 3

请注意,将无效持续时间添加到任何其他持续时间会导致无效持续时间。

Note that adding an invalid duration to any other duration results in an invalid duration.

减少时间 2.1.0+

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

通过减去时间来改变原始持续时间。

Mutates the original duration by subtracting time.

用于创建持续时间的相同键和简写在这里可以用作第二个参数。

The same keys and shorthands used to create durations can be used here as the second argument.

var a = moment.duration(3, 'd');
var b = moment.duration(2, 'd');
a.subtract(b).days(); // 1

请注意,将无效持续时间添加到任何其他持续时间会导致无效持续时间。

Note that adding an invalid duration to any other duration results in an invalid duration.

将时长与时间差一起使用 2.1.0+

var duration = moment.duration(x.diff(y))

你还可以将持续时间与 moment#diff 一起使用以获得两个 moment 之间的持续时间。为此,只需将 moment#diff 方法传递给 moment#duration,如下所示:

You can also use duration with moment#diff to get the duration between two moments. To do so, simply pass the moment#diff method into moment#duration as follows:

  var x = new moment()
  var y = new moment()
  var duration = moment.duration(x.diff(y))
  // returns duration object with the duration between x and y

有关 moment#diff 的更多信息,请参见 此处

See here for more information about moment#diff.

作为时间单位 2.1.0+

moment.duration().as(String);

作为 Duration#asX 的替代,你可以使用 Duration#as('x')。所有 速记键来自 moment#add 也适用于此。

As an alternate to Duration#asX, you can use Duration#as('x'). All the shorthand keys from moment#add apply here as well.

duration.as('hours');
duration.as('minutes');
duration.as('seconds');
duration.as('milliseconds');

所有单位的无效持续时间返回 NaN

Invalid durations return NaN for all units.

获取时间单位 2.1.0+

moment.duration().get(String);

作为 Duration#x() 获取器的替代品,你可以使用 Duration#get('x')。所有 速记键来自 moment#add 也适用于此。

As an alternate to Duration#x() getters, you can use Duration#get('x'). All the shorthand keys from moment#add apply here as well.

duration.get('hours');
duration.get('minutes');
duration.get('seconds');
duration.get('milliseconds');

所有单位的无效持续时间返回 NaN

Invalid durations return NaN for all units.

作为 JSON 2.9.0+

moment.duration().toJSON();

将持续时间对象序列化为 JSON 时,它将表示为 ISO8601 字符串。

When serializing a duration object to JSON, it will be represented as an ISO8601 string.

JSON.stringify({
    postDuration : moment.duration(5, 'm')
}); // '{"postDuration":"PT5M"}'

无效的持续时间以 json 表示形式返回 Invalid Date

Invalid durations return Invalid Date as json representation.

是否时长 1.6.0+

moment.isDuration(obj);

要检查变量是否为持续时间对象,请使用 moment.isDuration()

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

moment.isDuration() // false
moment.isDuration(new Date()) // false
moment.isDuration(moment()) // false
moment.isDuration(moment.duration()) // true
moment.isDuration(moment.duration(2, 'minutes')) // true

作为 ISO 8601 字符串 2.8.0+

moment.duration().toISOString();

返回 ISO 8601 标准 指定的字符串中的持续时间。

Returns duration in string as specified by ISO 8601 standard.

moment.duration(1, 'd').toISOString() // "P1D"

格式 PnYnMnDTnHnMnS 说明:

Format PnYnMnDTnHnMnS description:

单位 意义
P P 代表时期。放置在持续时间表示的开头。
Y 年份
M 月份
D
T 时间组件之前的指示符。
H 小时
M 分钟
S

语言环境 2.17.1+

moment.duration().locale();
moment.duration().locale(String);

你可以使用 locale(...) 获取或设置持续时间的区域设置。语言环境会影响持续时间的字符串方法,例如 humanize()。有关国际化的更多信息,请参阅 国际化 部分。

You can get or set the locale of a duration using locale(...). The locale will affect the duration's string methods, like humanize(). See the intl section for more information on internationalization generally.

moment.duration(1, "minutes").locale("en").humanize(); // a minute
moment.duration(1, "minutes").locale("fr").humanize(); // une minute
moment.duration(1, "minutes").locale("es").humanize(); // un minuto

humanize() 中的后缀也已国际化:

Suffixes in humanize() are also internationalized:

moment.duration(1, "minutes").locale("en").humanize(true); // in a minute
moment.duration(1, "minutes").locale("fr").humanize(true); // dans une minute
moment.duration(1, "minutes").locale("es").humanize(true); // en un minuto

moment.duration(-1, "minutes").locale("en").humanize(true); // a minute ago
moment.duration(-1, "minutes").locale("fr").humanize(true); // il y a une minute
moment.duration(-1, "minutes").locale("es").humanize(true); // hace un minuto

Moment 公开了一些可能对人们扩展库或编写自定义解析器有用的方法。

Moment exposes some methods which may be useful to people extending the library or writing custom parsers.

标准化单位 2.3.0+

moment.normalizeUnits(String);

Moment 的许多函数都允许调用者为单位枚举传入别名。例如,下面的所有 get 都是等效的。

Many of Moment's functions allow the caller to pass in aliases for unit enums. For example, all of the gets below are equivalent.

var m = moment();
m.get('y');
m.get('year');
m.get('years');

如果你要扩展该库,你可能需要访问 Moment 的设施,以便更好地使你的功能与 Moment 的功能保持一致。

If you're extending the library, you may want access to Moment's facilities for that in order to better align your functionality with Moment's.

moment.normalizeUnits('y');      // 'year'
moment.normalizeUnits('Y');      // 'year'
moment.normalizeUnits('year');   // 'year'
moment.normalizeUnits('years');  // 'year'
moment.normalizeUnits('YeARS');  // 'year'

无效时间 2.3.0+

moment.invalid(Object);

你可以创建自己的无效 Moment 对象,这对于制作你自己的解析器很有用。

You can create your own invalid Moment objects, which is useful in making your own parser.

var m = moment.invalid();
m.isValid();                      // false
m.format();                       // 'Invalid date'
m.parsingFlags().userInvalidated; // true

invalid 还接受一个指定要设置哪些解析标志的对象。这不会设置 userInvalidated 解析标志,除非它是指定的属性之一。

invalid also accepts an object which specifies which parsing flags to set. This will not set the userInvalidated parsing flag unless it's one of the properties specified.

var m = moment.invalid({invalidMonth: 'Actober'});
m.parsingFlags().invalidMonth; // 'Actober'

你无需指定 Moment 识别的解析标志;尽管如此,Moment 还是无效的,解析标志将由 parsingFlags() 返回。

You need not specify parsing flags recognized by Moment; the Moment will be invalid nonetheless, and the parsing flags will be returned by parsingFlags().

其他一些人制作了可能对你有用的 Moment.js 插件。

Some other people have made plugins for Moment.js that may be useful to you.

MSDate

如果你在 .NET 中使用 OLE 自动化日期,请查看 Markit On Demand 的 moment-msdate。使用此插件,你可以将 OA 日期格式化为 JavaScript 日期,反之亦然。

If you are using OLE Automation dates in .NET check out Markit On Demand's moment-msdate. Using this plugin allows you to format OA dates into JavaScript dates and vice-versa.

moment 转换为 OA 日期:

Convert a moment to an OA date:

moment().toOADate(); // a floating point number

或者,将 OA 日期转换为 moment

Or, convert an OA date to a moment:

moment.fromOADate(41493); // Wed Aug 07 2013 00:00:00 GMT-0600 (MDT)

更多信息和详细文档可以在 GitHub 上找到,地址为 http://markitondemand.github.io/moment-msdate/

More information and detailed docs can be found on GitHub at http://markitondemand.github.io/moment-msdate/.

Java 日期格式解析器

npm install moment-jdateformatparser

如果你想使用 java.text.DateFormat,你可以使用这个插件。

If you want to work with the java.text.DateFormat you can use this plugin.

例如,

For example,

moment("2013-12-24 14:30").formatWithJDF("dd.MM.yyyy");  // returns the formatted date "24.12.2013"
moment().toJDFString("DD.MM.YYYY");  // returns the Java format pattern "dd.MM.yyyy"

存储库位于 github.com/MadMG/moment-jdateformatparser

The repository is located at github.com/MadMG/moment-jdateformatparser.

日期范围

npm install moment-range

如果你需要处理日期范围,可以使用 Gianni Chiappetta 的插件 moment-range

If you need to work with date ranges, you can use Gianni Chiappetta's plugin moment-range.

文档可以在主页 github.com/rotaready/moment-range 上找到。

Documentation can be found on the homepage github.com/rotaready/moment-range.

它也可以在下面的存储库中用于网络。

And it is also available for the web at the repository below.

存储库位于 github.com/rotaready/moment-range

The repository is located at github.com/rotaready/moment-range.

Twix

npm install twix

另一个范围插件是 Isaac Cambron 的库 Twix。它具有许多与范围相关的功能,并且擅长以可读的方式格式化范围。例如,

Another range plugin is Isaac Cambron's library Twix. It has many range-related features and excels at formatting ranges readably. For example,

var t = moment("1/25/1982 9:30 AM").twix("1/25/1982 1:30 PM");
t.isCurrent(); // false
t.count('minutes'); // 241
t.format();  // 'Jan 25, 1982, 9:30 AM - 1:30 PM'
t.simpleFormat("h:m"); // '9:30 - 1:30'

所有选项和功能的完整文档是 此处

Full documentation of all the options and features is here.

它在 npm 上可用,如下所示:

It's available on npm like so:

npm install twix

或者只是从 此处 中获取 JS 文件。

Or just grab the JS file from here.

精确范围

npm install moment-precise-range-plugin

Rob Dawson 编写的 精确范围 插件可用于显示准确的、人类可读的日期/时间范围表示:

The Precise Range plugin, written by Rob Dawson, can be used to display exact, human-readable representations of date/time ranges:

moment("2014-01-01 12:00:00").preciseDiff("2015-03-04 16:05:06");
 // 1 year 2 months 3 days 4 hours 5 minutes 6 seconds
moment.preciseDiff("2014-01-01 12:00:00", "2014-04-20 12:00:00");
// 3 months 19 days

要获取原始数值而不是字符串,请将值 true 作为第三个参数传递给该方法:

To obtain the raw numeric values rather than a string, pass the value true as the third argument to the method:

moment.preciseDiff(m1, m2, true); 
// {years : 0, months : 1, days : 2, hours : 3, minutes : 4, seconds : 5, firstDateWasLater : false}

ISO 日历

npm install moment-isocalendar

如果你正在寻找类似 Python 的等历法,你可以使用 Rocky Meza 的插件

If you are looking for a Python-like isocalendar method, you can use Rocky Meza's plugin

moment-isocalendar

立即调用 isocalendar 方法将返回如下数组:

Calling the isocalendar method on a moment will return an array like the following:

[year, week_of_year, day_of_week, minutes_since_midnight]

moment().isocalendar(); // [2012, 8, 5, 870]

你还可以从等历表重建 moment。

You can also reconstruct a moment from a isocalendar array.

moment.fromIsocalendar([2011, 51, 5, 870]).format('LLLL');
// "Friday, December 23 2011 2:30 PM"

存储库位于 github.com/fusionbox/moment-isocalendar

The repository is located at github.com/fusionbox/moment-isocalendar.

Jalaali 日历

npm install moment-jalaali

如果你想使用 Jalaali 日历系统(Jalali、波斯语、Khorshidi 或 Shamsi),你可以使用 Behrang Noruzi Niya 的插件 moment-jalaali

If you want to work with Jalaali calendar system (Jalali, Persian, Khorshidi or Shamsi), you can use Behrang Noruzi Niya's plugin moment-jalaali.

安装后,它将封装 moment 并且瞬间将能够格式化和解析 Jalaali 年份和月份。这是一个简短的例子:

When installed, it will wrap moment and moment will be able to format and parse Jalaali years and months. Here is a short example:

var m = moment('1360/5/26', 'jYYYY/jM/jD'); // Parse a Jalaali date.
m.format('jYYYY/jM/jD [is] YYYY/M/D'); // 1360/5/26 is 1981/8/17

存储库位于 github.com/behrang/moment-jalaali

The repository is located at github.com/behrang/moment-jalaali.

Hijri 日历

npm install moment-hijri

如果你想使用 Hijri 日历,那么你可以使用 moment-hijri 插件。moment-hijri 是基于 Umm al-Qura 计算的回历农历 moment 插件。本插件由 Suhail Alkowaileet 开发。

If you want to work with Hijri calendar then you can use moment-hijri plugin. moment-hijri is a moment plugin for the Hijri lunar calendar based on Umm al-Qura calculations. This plugin is developed by Suhail Alkowaileet.

当你安装它时,它会封装 moment,你将能够解析 Hijri 日期。这是一个简短的例子:

When you install it, it will wrap moment and you will be able to parse Hijri dates. Here is a short example:

m = moment('1410/8/28', 'iYYYY/iM/iD'); // Parse a Hijri date.
m.format('iYYYY/iM/iD [is] YYYY/M/D'); // 1410/8/28 is 1990/3/25

存储库位于 github.com/xsoh/moment-hijri

The repository is located at github.com/xsoh/moment-hijri.

Recur

npm install moment-recur

如果你需要处理重复日期,可以使用 Casey Trimm 的插件 moment-recur

If you need to work with recurring dates, you can use Casey Trimm's plugin moment-recur.

该插件将允许你创建基于长度的间隔(天、周等)和基于日历的间隔(daysOfMonth、monthsOfYear 等)。

This plugin will allow you to create length-based intervals (days, weeks, etc.) and calendar-based intervals (daysOfMonth, monthsOfYear, etc.).

它提供了一个 matches 函数来测试一个日期是否根据规则集重复出现,以及生成器函数来获取一系列中的下一个和上一个日期。

It provides a matches function to test whether a date recurs according to the rules set, as well as generator functions to get the next and previous dates in a series.

可以在 github.com/c-trimm/moment-recur 找到存储库、文档和更多示例

The repository, documentation, and many more examples can be found at github.com/c-trimm/moment-recur

var interval = moment( "01/01/2014" ).recur().every(2).days(); // Length Interval
interval.matches( "01/03/2014" ); // true
interval.next( 2, "L" ); // ["01/03/2014", "01/05/2014"]
interval.forget( "days" ); // Remove a rule
interval.dayOfMonth( 10 ); // Calendar Interval
interval.matches( "05/10/2014" ); // true
interval.previous( 2, "L" ); // ["12/10/2013", "11/10/2013"]

Twitter

如果你尝试像 Twitter 那样为推文设置时间格式,你可以使用 @hijonathanmoment.twitter 插件。

If you're trying to format times for tweets like the way Twitter does, you can use the moment.twitter plugin by @hijonathan.

这是显示人类可读时间戳的短版本和长版本的简单方法。

It's a simple way to display both short and long versions of human-readable timestamps.

moment().subtract(5, 'hours').twitterLong();
// 5 hours

是的,它进行智能多元化。

Yes, it does smart pluralization.

moment().subtract(1, 'hour').twitterLong();
// 1 hour

对你来说还不够短?

Not short enough for you?

moment().subtract(6, 'days').twitterShort();
// 6d

财政季度

如果你需要 财政、日历或学术宿舍,你可以使用 @robgallenmoment-fquarter 插件。

If you ever have need for Fiscal, Calendar or Academic quarters, you can use the moment-fquarter plugin by @robgallen.

最简单的是,只需在任何 moment 对象上调用 fquarter 方法。它返回一个格式化的字符串,四月是第一季度。

At its simplest, just call the fquarter method on any moment object. It returns a formatted string with April being the first quarter.

moment("2013-01-01").fquarter();
// Q4 2012/13

你可以将任何月份作为起始季度,例如 七月

You can pass in any month as the starting quarter, e.g. July

moment("2013-01-01").fquarter(7);
// Q3 2012/13

如果你想要日历季度,从一月开始

If you want calendar quarters, start in January

moment("2013-01-01").fquarter(1);
// Q1 2013

解析日期格式

npm install moment-parseformat

此插件提取日期/时间字符串的格式。

This plugin extracts the format of a date/time string.

var format = moment.parseFormat('Thursday, February 6th, 2014 9:20pm');
// dddd, MMMM Do, YYYY h:mma
moment().format(format); // format

这允许创建智能日期输入,让你的用户设置日期/时间,并让你提取用户的首选格式以供将来使用。在 minutes.io 找到它的用法示例。

That allows to create smart date inputs that let your users set a Date/Time and lets you extract the user's preferred format for future usage. Find an example usage of it at minutes.io.

该插件由 @gr2m 编写。链接:演示 | 源码

The Plugin has been authored by @gr2m. Links: Demo | Source

四舍五入

npm install moment-round

该插件会将日期/时间舍入到给定的时间间隔。

This plugin will round date/time to a given interval.

例如,

For example,

require('moment-round');
var m = new moment(); // 2015-06-18 15:30:19
m.round(5, 'seconds'); // 2015-06-18 15:30:20
m.ceil(3, 'minutes'); // 2015-06-18 15:33:00
m.floor(16, 'hours'); // 2015-06-18 00:00:00
m.ceil(21, 'hours'); // 2015-06-18 21:00:00
m.ceil(20, 'hours'); // 2015-06-19 00:00:00

存储库位于 github.com/WebDevTmas/moment-round

The repository is located at github.com/WebDevTmas/moment-round.

转换

bower install moment-transform

moment-transform 是一个通过模式操作日期的插件。你可以对 Moment 实例的各个部分(小时、月份……)使用基本操作 – 设置/添加/减去。

moment-transform is a plugin that manipulated dates through patterns. You can use basic operations –set/add/subtract– on individual parts (hours, month, …) of a Moment instance.

moment().transform('YYYY-MM-+01 00:00:00.000'); // Tonight at midnight
moment().transform('14:30:00.000'); // Today, 2:30 pm
moment().transform('YYYY-MM--30 00:00:00.000'); // 30 days ago

可选参数允许你指定自定义模式并强制使用严格的模式(默认情况下,非字母字符在传递的字符串中不是强制性的)。

Optional parameters lets you specify custom patterns and force strict pattern usage (non-alphabetic characters are not mandatory in passed string by default).

moment().transform('+01MMYYYY', 'DD/MM/YYYY', false); // Tomorrow, same time
moment().transform('+01MMYYYY', 'DD/MM/YYYY', true); // Invalid date

你可以在 此处 上看到它,而存储库是 此处

You can see it live there while the repository is here.

台湾日历

npm install moment-taiwan

如果你想使用台湾日历系统,你可以使用 Bradwoo8621 的插件 moment-taiwan

If you want to work with Taiwan calendar system , you can use Bradwoo8621's plugin moment-taiwan.

安装后,将 moment 封装起来,瞬间就可以格式化解析台年了。这是一个简短的例子:

When installed, it will wrap moment and moment will be able to format and parse Taiwan years. Here is a short example:

m = moment('104/01/01', 'tYY/MM/DD') // Parse a Taiwan date
m.format('tYY/MM/DD [is] YYYY/M/D') // 104/01/01 is 2015/01/01

m.twYear() // 104

存储库位于 github.com/bradwoo8621/moment-taiwan

The repository is located at github.com/bradwoo8621/moment-taiwan.

计时器

npm install moment-timer

这是一个允许使用计时器的 Moment.js 插件,它提供比原生 JavaScript 计时器更多的控制。它基本上是对 JavaScript 自己的 setInterval 和 setTimeout 的重写。

This is a Moment.js plugin that allows the use of timers, which offer much more control than the native JavaScript timers. It's basically a rewrite of JavaScripts own setInterval and setTimeout.

例如,

For example,

var timer = moment.duration(5, "seconds").timer({loop: true}, function() {
  // Callback
});

存储库位于 github.com/SeverinDK/moment-timer

The repository is located at github.com/SeverinDK/moment-timer.

商业

npm install moment-business

这是一个 Moment.js 库,允许西方工作周的 Moment 操作:每周 7 天,周六和周日为非工作日。

This is a Moment.js library that allows Moment operations for Western work weeks: 7 day weeks where Saturday and Sunday are non-work days.

例如,

For example,

import business from 'moment-business';

// true if the moment is Mon-Fri, false otherwise
business.isWeekDay(someMoment);

// Adds five work days to the Moment
business.addWeekDays(someMoment, 5);

存储库位于 github.com/jmeas/moment-business

The repository is located at github.com/jmeas/moment-business.

短日期格式化器

如果想短时间格式化,可以使用 @researchgatemoment-shortformat 插件。

If you want to format times in a short way, you can use the moment-shortformat plugin by @researchgate.

它基于并类似于 moment.twitter 插件,但具有不同的输出。

It is based on and similar to the moment.twitter plugin but has a different output.

moment().subtract(5, 'hours').short();
// 5h ago
moment().add(5, 'hours').short();
// in 5h

你还可以禁用 相对时间模板

You can also disable the use of the relative time templates

moment().subtract(1, 'hour').short(false);
// 1h

如果日期在未来或过去太远,它会这样显示

If the date is too far in the future or the past it will display like that

moment().subtract(500, 'days').short();
// 5 Mar, 1970

德国假期(Feiertag)

npm install moment-feiertage --save

这个 (moment-feiertage) 是一个 Moment.js 插件,用于确定日期是否是德国假期。假期取自维基百科 (de)。确定一个日期是否是假期有点复杂,因为宗教节日每年都不同,而且在德国 16 个州内也不尽相同。

This (moment-feiertage) is a Moment.js plugin to determine if a date is a German holiday. Holidays are taken from Wikipedia (de). It's a bit complicated to determine if a date is a holiday, because religious holidays vary every year and differ within the 16 German states.

DaniSchenk 制作。

Made by DaniSchenk.

var someDateInSomeStates = moment('2018-11-01').isHoliday(['BW', 'SH', 'TH']);
/* returns {
  allStates: false,
  holidayName: 'Allerheiligen',
  holidayStates: [ 'BW' ],
  testedStates: [ 'BW', 'SH', 'TH' ]
}*/

存储库位于 github.com/DaniSchenk/moment-feiertage

The repository is located at github.com/DaniSchenk/moment-feiertage.