momentjs

总览 (Overview)

Time management is always a hot topic for discussion and it’s no different in case of JavaScript applications! Managing date and time, especially when different formats and timezones are to be supported, requires a mature library in most applications.

时间管理一直是讨论的热门话题,对于JavaScript应用程序也是如此! 管理日期和时间,尤其是在要支持不同格式和时区的情况下,在大多数应用程序中都需要成熟的库。

MomentJS is a JavaScript library for parsing, validating, manipulating, and formatting date and time values in the browser and Node.js environments. Available as a JS package for most of the bundlers and as a JS script that can be imported directly from the CDN, moment.js seems to be a solid solution for all date-time needs.

MomentJS是一个JavaScript库,用于在浏览器和Node.js环境中解析,验证,操纵和格式化日期和时间值。 作为大多数捆绑程序的JS软件包和可以直接从CDN导入的JS脚本,moment.js似乎是满足所有日期时间需求的可靠解决方案。

强调 (Highlights)

Getting started with moment.js is pretty easy. It can be installed by running the command npm install moment .

moment.js入门非常简单。 可以通过运行命令npm install moment

/* Babel or ES6 */
import moment from 'moment';/* Node or requireJs */var moment = require('moment');

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

注意:在2.4.0中,不建议使用全局导出的`moment`对象。 它将在下一个主要版本中删除。

Moment operates by creating a wrapper over the JS’s native Date.prototype object and the object returned is mutable.

Moment通过在JS的本机Date.prototype对象上创建包装器来操作,并且返回的对象是可变的。

解析和提取 (Parsing and Extract)

Getting the current date-time is as simple as instantiating a moment object. The returned value will be a Moment object, from which a simple date and time string can be extracted using toString() method.

获取当前日期时间就像实例化矩对象一样简单。 返回的值将是一个Moment对象,可以使用toString()方法从中提取简单的日期和时间字符串。

const current = moment(); // current.toString() = "Wed Jul 29 2020 10:44:07 GMT+0530"

Other methods in the Moment object can be used to extract the values of specific parts or to set them. Some of the commonly used ones are listed below:

Moment对象中的其他方法可用于提取特定零件的值或进行设置。 下面列出了一些commonly的:

Some extract method examples
一些提取方法示例

Moment provides powerful date-time parsing and supports all ISO 8601 strings. Formats not defined under this ISO specification are also supported but it depends on the browser’s ability to parse that format via the native Date object.

Moment提供了强大的日期时间解析,并支持所有ISO 8601字符串 。 还支持未在此ISO规范下定义的格式,但它取决于浏览器通过本机Date对象解析该格式的能力。

A couple of ways to parse a date-time string or object are as below. Do note that by default, Moment provides timestamps in local mode. If you need it in UTC, it has to be explicitly specified.

解析日期时间字符串或对象的几种方法如下。 请注意,默认情况下,Moment在本地模式下提供时间戳。 如果您在UTC中需要它,则必须明确指定它。

没有格式说明符 (Without format specifier)

Some examples of simple parsing without specifying a format string would be:

在不指定格式字符串的情况下进行简单解析的一些示例如下:

moment("2020-12-30"); // Mon Dec 25 1995 00:00:00 GMT+0530moment("2020W065"); // Basic (short) ISO8061 format with week and weekday - week 6 and 5th day in 2020 - Fri Feb 07 2020 00:00:00 GMT+0530moment(2318788876406) // Unix Epoch value - Thu Jun 25 2043 01:31:16 GMT+0530moment({ year:1996, month:11, day:13, hour:23, minute:10, second:30, millisecond:123}) // Fri Dec 13 1996 23:10:30 GMT+0530 - Observe that month starts from 0!moment(new Date(1996, 11, 13)) // JS Date object - Fri Dec 13 1996 00:00:00 GMT+053moment([2020, 6, 29]) // Wed Jul 29 2020 00:00:00 GMT+0530 - Format is [year, month, day, hour, minute, second, millisecond]moment.utc("1996-12-13", "YYYY-MM-DD") // In UTC - Fri Dec 13 1996 00:00:00 GMT+0000moment.parseZone("2020-01-01T00:00:00+08:00") // With specified timezone - Wed Jan 01 2020 00:00:00 GMT+0800

带有格式说明符 (With format specifier)

The format of the value to be parsed can be specified for better parsing and the supported format strings can be found here

可以指定要解析的值的格式以进行更好的解析,并且可以在此处找到受支持的格式字符串

moment('24-12-2020 11:15:00', "DD-MM-YYYY hh:mm:ss", true) // Thu Dec 24 2020 11:15:00 GMT+0530

In normal parsing, the non-numeric characters are usually ignored when the format is specified! This essentially means moment("13-12-1996", “DD-MM-YYYY")is treated the same as moment("13/12/1996", “DD-MM-YYYY"). This might provide inconsistent results when parsing both time and date and hence strict mode is recommended to be used by passing a true boolean as the last parameter as shown in the example above.

在普通解析中,指定格式时通常会忽略非数字字符! 从本质moment("13-12-1996", “DD-MM-YYYY")这意味着moment("13-12-1996", “DD-MM-YYYY")moment("13/12/1996", “DD-MM-YYYY") 。 如上例所示,这在解析时间和日期时可能会提供不一致的结果,因此建议通过将true布尔值作为最后一个参数来使用严格模式。

Multiple formats can also be provided to the parser, in which case Moment will try to parse the value by picking the parser from the list provided in a sequential manner and use the first valid one it finds from the list

解析器还可以提供多种格式,在这种情况下,Moment会尝试通过按顺序从提供的列表中选择解析器并使用从列表中找到的第一个有效解析器来解析值。

moment("13-12-1996", ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"]) // Uses the last format in the list

Locale can also be specified for the parsing by providing a locale string

还可以通过提供语言环境字符串来指定语言环境进行解析

moment('2020 juillet', 'YYYY MMM', 'fr') // Wed Jul 01 2020 00:00:00 GMT+0530

Explicit special formats can also be specified for parsing like ISO 8061

也可以为解析指定显式特殊格式,例如ISO 8061

moment("1996-12-13T05:06:07", ["YYYY", moment.ISO_8601, "YYYY-MM-DD"])

检测无效日期 (Detecting invalid dates)

Moment provides a simple isValid() method to determine if a valid date object is provided. For example

Moment提供了一个简单的isValid()方法来确定是否提供了有效的日期对象。 例如

moment("2020 13", "YYYY MM").isValid() // false (invalid month)moment("2020 13", "YYYY MM").invalidAt() // 1 - Since the invalid month provided here (13) is the 2nd value, it's position index of 1 is returnedmoment("2020 12", "YYYY MM").isValid() // true

Since the parser is not very strict, unexpected behaviors/issues can crop up like:

由于解析器不是很严格,所以意外的行为/问题可能会出现:

moment('2020 is a date', 'YYYY-MM-DD').isValid() // true as 2016 matches YYYY

Hence, extra care should be taken while checking validity with Moment and it's strict mode is advised to be used always.

因此,在使用Moment检查有效性时应格外小心,建议始终使用strict模式。

操作方式 (Manipulations)

Moment supports almost all of your date time manipulations used regularly like add, subtract, min and max. Some of the unique ones include the start of time and the end of time manipulations. Examples below showcase some of the ways you can manipulate the values of the moment object you possess!

Moment支持您定期使用的几乎所有日期时间操作,例如加,减,最小和最大。 一些独特的功能包括时间的开始和时间的结束。 下面的示例展示了一些您可以操纵拥有的moment对象值的方法!

  • Add and Subtract

    加减

moment().add(7, 'days') // Add 7 days to current date - Tue Aug 04 2020 to Tue Aug 11 2020moment().add({ days:7, months: 2}) // Add 7 days and 2 months to current date - Tue Aug 04 2020 to Sun Oct 11 2020moment().subtract(1.5, 'months') // Subtract one and half months from today's date - Tue Aug 04 2020 to Thu Jun 04 2020

If you pass decimal values to the duration values of days or months above, it will be rounded to the nearest integer. Weeks, quarters and years are converted to days first and then rounded.

如果将十进制值传递给以上天数或月份的持续时间值,它将四舍五入为最接近的整数。 星期,季度和年首先转换为天,然后四舍五入。

  • Start and End of time

    时间的开始和结束

These are interesting methods that mutate the original moment object value to the start or the end value of the unit specified.

这些有趣的方法将原始moment对象的值更改为指定单位的开始或结束值。

moment().startOf('year') // Sets to January 1st 12:00 am of the current year - Wed Jan 01 2020 00:00:00moment().endOf('year') // Sets to December 31st 11:59 pm of the current year - Thu Dec 31 2020 23:59:59
  • Local and UTC values

    本地和UTC值

The local and UTC values for a moment object and the offsets of the same can be obtained as shown below. The local and utc methods set a flag in the original moment object and all further retrieval from them will give the corresponding values.

力矩对象的本地和UTC值及其偏移量可以如下所示获得。 localutc方法在原始moment对象中设置了一个标志,从它们中进行的所有进一步检索将给出相应的值。

const utcDate = moment.utc("2020-01-13 15:00")
utcDate.hours() // 15
utcDate.minutes() // 0
utcDate.local() // GMT +05:30
utcDate.hours() // 20
utcDate.minutes() // 30const localDate = moment("2020-01-13 15:00") // GMT +05:30
utcDate.hours() // 15
utcDate.minutes() // 0
utcDate.utc()
utcDate.hours() // 9
utcDate.minutes() // 30moment().utcOffset() // Get offset from utc in minutes - 330 for GMT+05:30
moment().utcOffset(8); // Set offset in hours when value in argument is less than 16 or greater than -16, else in minutes, on the moment object returned.

格式化和查询 (Formatting and Querying)

Formatting and querying are some of the most used features, especially in front-end applications, for fetching and displaying date-time values in the required format. One of the core functions offered by Moment is format. It accepts the format string (whose supported values can be found here) and returns the value accordingly. If no string is passed, it returns in ISO8601 format as standard. This standard format can also be overridden by setting the format string to the defaultFormat property of the moment object.

格式化和查询是一些最常用的功能,尤其是在前端应用程序中,用于以所需格式获取和显示日期时间值。 Moment提供的核心功能之一是format 。 它接受格式字符串(可以在此处找到支持的值)并相应地返回值。 如果未传递任何字符串,则它以ISO8601格式作为标准返回。 通过将格式字符串设置为moment对象的defaultFormat属性,也可以覆盖此标准格式。

moment().format() // ISO8601 format - 2020-08-05T10:09:02+05:30moment().format('dddd, MMMM Do YYYY, h:mm:ss') // Wednesday, August 5th 2020, 10:10:27moment().format('[The time is ] h:mm:ss a') // The time is 10:10:27 am

Though moment offers many more formatting options, some of the uncommon ones are:

尽管moment提供了更多的格式设置选项,但一些不常见的选项是:

moment().toArray() // [2020, 7, 5, 10, 18, 36, 699]moment().toDate() // Returns JS's native Date objectmoment().toObject() // { "years": 2020, "months": 7, "date": 5, "hours": 10, "minutes": 21, "seconds": 5 "milliseconds": 108 }moment().inspect() // Returns the string form of the moment command that can be used to get a value - moment("2020-08-05T10:22:30.574")

Some of the useful query methods offered by moment include:

此刻提供的一些有用的查询方法包括:

moment('2020-10-20').isBefore('2010-10-30') // false
moment('2015-10-20').isBefore('2020-01-01', 'year') // truemoment('2020-05-20').isSame('2020-05-20') // truemoment('2021-10-20').isAfter('2020-10-15') // truemoment().isDST() // Checks if the current date-time is in daylight saving timemoment().isLeapYear() // Checks if the year in the moment object is a leap yearmoment.isDate(new Date()) // true - Checks if the object in the parameter is a native JS Date object

其他实用程序 (Other Utilities)

Moment also provides support of internationalization, plugins to handle date-time in formats of common languages like Java, custom values for locales, and operating in terms of durations. Let’s take a sneak peek into the few tricks it has to offer!

Moment还提供国际化支持,以通用语言(如Java)格式处理日期时间的插件,语言环境的自定义值以及按持续时间进行操作。 让我们先来看看它提供的一些技巧!

  • i18n

    i18n

Internationalization is natively supported by `Moment` and global and object-specific local settings are allowed. The global locale setting can be done using the `locale` method. Note that the package comes with en-us locale as default and others have to be manually loaded. Many of the commonly used locales are readily available for usage in the package sources under locale directory and only require the file to be loaded during runtime.

Moment本身就支持国际化,并且允许全局和特定于对象的本地设置。 全局语言环境设置可以使用locale方法完成。 请注意,该软件包默认带有en-us语言环境,而其他语言则必须手动加载。 许多常用的语言环境都可以在locale目录下的包源中使用,并且只需要在运行时加载文件即可。

pro-tip: Getting rid of the locales you don’t need from the package sources helps reduce the bundle size!

专家提示:摆脱软件包来源中不需要的语言环境有助于减小软件包的大小!

moment.locale("fr", { ...configObject }) //setting French locale

The keys to be passed to the configObject above can be found over at moment docs.

可以在docs时刻找到要传递给上述configObject的密钥。

The objects loaded before setting the locale globally will not be affected by the locale change. A list locales can also be specified and moment will pick the first available one for use. In the case of locale specifier substrings like en-au, Moment will search from most-specific to least-specific and load the aptest one it finds.

全局设置语言环境之前加载的对象将不受语言环境更改的影响。 还可以指定列表语言环境, moment将选择第一个可用的语言环境。 对于诸如en-au类的语言环境说明符子字符串,Moment将从最特定的搜索到最不特定的搜索,并加载找到的aptest。

moment.locale(['gb', 'fr']) // will use fr when gb has not been already loaded

For changing locales for specific objects, the locale method on the instance can be called:

为了更改特定对象的locale ,可以在实例上调用locale方法:

const tempLocale = moment()
tempLocale.locale('fr') // changes locale only for this instance

Loading locale files varies as per the platform. Please check the Moment docs for your platform of choice.

加载区域设置文件因平台而异。 请检查Moment文档以了解您选择的平台。

The info of the currently loaded locale can be fetched using the localeData method:

可以使用localeData方法获取当前加载的语言环境的信息:

moment.localeData('fr') // returns the config of the fr locale
  • Locale Customization

    语言环境自定义

Many of the values and attributes of the package can be easily modified by using the locale method and it is recommended that you define your own custom locale and load it if you are gonna end up modifying an existing locale extensively for your use case. You can also use updateLocale method if you are looking into modifying only specific aspects of a locale.

可以使用locale方法轻松地修改包的许多值和属性,如果最终要针对用例大量修改现有的语言环境,建议您定义自己的自定义语言环境并加载它。 如果您只考虑修改语言环境的特定方面,也可以使用updateLocale方法。

For example, to update the minimal weekday abbreviations (the shorter form of a weekday, like “Sun” for Sunday) for a locale, you can do:

例如,要更新语言环境的最小工作日缩写(工作日的缩写形式,例如星期日为“ Sun”),您可以执行以下操作:

moment.updateLocale('en', {
weekdaysMin : ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
}
);

One of the aspects you might find useful to update would be the message returned for an Invalid date.

您可能发现对更新有用的方面之一是返回无效日期的消息。

moment.updateLocale("en", {
invalidDate: "INVALID_DATE"
});

Similarly, almost all aspects can be modified for a locale and we highly recommend spending some time in setting up a custom locale extending a base locale or modifying your existing one to suit your use cases at the beginning of your project.

同样,几乎所有方面都可以针对语言环境进行修改,我们强烈建议您花一些时间来建立可扩展基本语言环境的自定义语言环境,或在项目开始时修改现有的语言环境以适合您的用例。

  • Duration Objects

    持续时间对象

Moment can be used to create and use duration objects. As their name suggests, they contain time or date durations as the values instead of the typical date-time values. For example:

Moment可用于创建和使用持续时间对象。 顾名思义,它们包含时间或日期持续时间作为值,而不是典型的日期时间值。 例如:

moment.duration(3, 'months') // returns an object containing 3 months duration value

Like normal moment objects, these can be manipulated with add, subtract, and similar other methods. One of the interesting aspects of this is the humanize method. This method returns the durations in a humanized or plain English way. For example, a duration of 1 month in a humanized way would look like:

像法线moment对象一样,可以使用加,减和其他类似方法来操纵这些对象。 有趣的方面之一是humanize方法。 此方法以人性化或简单的英语方式返回持续时间。 例如,以人性化的方式进行的1个月的持续时间如下所示:

moment.duration(1, "month").humanize() // "a month"

This method also supports suffixes as shown below:

此方法还支持后缀,如下所示:

moment.duration(5, "minutes").humanize(true) // "in 5 minutes"moment.duration(-5, "minutes").humanize(true) // "5 minutes ago"
  • Plugins

    外挂程式

Though not extensive, Moment does support plugins and you can find quite a few by the community, helping you tackle those niche use cases which plain moment can’t cater for!

尽管不广泛,但Moment确实支持插件,并且您可以在社区中找到很多插件,从而帮助您解决那些普通时刻无法满足的利基用例!

Most of the plugins revolve around providing support for different calendars like Jalaali, Hijri, etc., language-specific date-time formats like Strftime, MSDate, Java DateFormat, etc. and catering for very specific use cases like getting Twitter’s time format or checking if a given date is a German holiday.

大多数插件都围绕为以下方面提供支持:Jalaali,Hijri等不同的日历; Strftime,MSDate,Java DateFormat等语言特定的日期时间格式;以及适应非常特定的用例,例如获取Twitter的时间格式或检查如果给定的日期是德国假期。

We recommend checking out the list of plugins in the official documentation along with simply doing a Google search for finding a plugin to cater to your specific needs.

我们建议您检查一下官方文档中的插件列表,然后简单地通过Google搜索来查找可满足您特定需求的插件。

  • Extension

    延期

If you are looking into extending or writing custom parsers for Moment, then some of the methods like normalizeUnits (allows normalizing aliases of unit enums) and invalid (allows the creation of invalid Moment objects) are provided. As these are not used extensively for regular use cases, we recommend checking out Moment’s Documentation if you are looking for more info on these.

如果您正在寻找扩展或编写Moment的自定义解析器的方法,那么可以提供一些方法,例如normalizeUnits (允许对单位枚举的别名进行规范化)和invalid (允许创建无效的Moment对象)。 由于这些未在常规使用案例中广泛使用,因此,如果您需要有关这些的更多信息,建议您查阅Moment文档 。

结论 (Conclusion)

Moment is a powerful and extensive date-time management library that can more-or-less handle any type of manipulation or querying you may throw at it! Operating as a wrapper on top of the native JS Date object, it follows an OOPS approach to handling the objects. Though it does not compromise on its feature set, it does have it’s a fair share of drawbacks like very bulky package size, little to no support for tree-shaking, and mutability of the objects.

Moment是一个功能强大且广泛的日期时间管理库,可以或多或少地处理您可能会抛出的任何类型的操作或查询! 作为本地JS Date对象的包装,它遵循OOPS方法处理对象。 尽管它在功能上没有妥协,但确实有很多缺点,例如非常大的包装尺寸,很少或根本不支持树状摇晃以及对象的可变性。

The set of functionalities we have covered in this guide is in no means exhaustive and the package has many more interesting and unique features up its sleeve. Do check it’s docs and guides to get the complete picture!

我们在本指南中介绍的功能集绝不是详尽无遗的,并且该软件包在袖子上具有更多有趣且独特的功能。 请检查它的文档和指南以获取完整图片!

In conclusion, if you are seeking a specific functionality that exists only in Moment or your project already uses it, then it’s better to stick to it, otherwise, we can look into simpler but performant libraries like date-fns (Our in-depth guide and review for date-fns can be found here).

总之,如果您正在寻找仅存在于Moment中的特定功能,或者您的项目已经使用了它,那么最好坚持使用它,否则,我们可以研究更简单但性能更好的库,例如date-fns (我们的深入指南并在此处找到date-fns评论)。

评估指标 (Evaluation Metrics)

Evaluation of the package
包装评估

翻译自: https://medium/javascript-in-plain-english/momentjs-a-concise-date-handling-experience-3abad32f7691

momentjs

更多推荐

momentjs_MomentJS:简洁的日期处理体验!