Welcome to our ultimate guide on the JavaScript Date
object and Moment.js. This tutorial will teach you everything you need to know about working with dates and times in your projects.
欢迎使用我们关于JavaScript Date
对象和Moment.js的最终指南。 本教程将教您有关在项目中使用日期和时间的所有知识。
Date
对象 (How to Create a Date
Object)const now = new Date();
// Mon Aug 10 2019 12:58:21 GMT-0400 (Eastern Daylight Time)
const specifiedDate = new Date(2019, 4, 29, 15, 0, 0, 0);
// Wed May 29 2019 15:00:00 GMT-0400 (Eastern Daylight Time)
The syntax is Date(year, month, day, hour, minute, second, millisecond)
.
语法为Date(year, month, day, hour, minute, second, millisecond)
。
Note that the months are zero-indexed, beginning with January at 0 and ending with December at 11.
请注意,月份是零索引的,从1月的0开始到12月的11结束。
const unixEpoch = new Date(0);
This represents the time at Thursday, January 1st, 1970 (UTC), or the Unix Epoch time. The Unix Epoch is important because it's what JavaScript, Python, PHP, and other languages and systems use internally to calculate the current time.
这表示1970年1月1日星期四(UTC)的时间,即Unix Epoch的时间。 Unix Epoch非常重要,因为它是JavaScript,Python,PHP以及其他语言和系统在内部用于计算当前时间的工具。
new Date(ms)
returns the date of the epoch plus the number of milliseconds you pass in. In a day there's 86,400,000 milliseconds so:
new Date(ms)
返回纪元的日期加上您传递的毫秒数。一天中有86,400,000毫秒,因此:
const dayAfterEpoch = new Date(86400000);
will return Friday, January 2nd, 1970 (UTC).
将于1970年1月2日,星期五(UTC)返回。
const stringDate = new Date('May 29, 2019 15:00:00');
// Wed May 29 2019 15:00:00 GMT-0400 (Eastern Daylight Time)
Getting the date this way is very flexible. All of the examples below return valid Date
objects:
通过这种方式获取日期非常灵活。 下面的所有示例都返回有效的Date
对象:
new Date('2019-06') // June 1st, 2019 00:00:00
new Date('2019-06-16') // June 16th, 2019
new Date('2019') // January 1st, 2019 00:00:00
new Date('JUNE 16, 2019')
new Date('6/23/2019')
You can also use the Date.parse()
method to return the number of milliseconds since the epoch (January 1st, 1970):
您还可以使用Date.parse()
方法返回自纪元(1970年1月1日)以来的毫秒数:
Date.parse('1970-01-02') // 86400000
Date.parse('6/16/2019') // 1560610800000
When passing a date string without setting a time zone, JavaScript assumes the date/time are in UTC before converting it to your browser's time zone:
当传递日期字符串而不设置时区时,JavaScript会在将日期/时间转换为浏览器时区之前假定日期/时间为UTC:
const exactBirthdate = new Date('6/13/2018 06:27:00');
console.log(exactBirthdate) // Wed Jun 13 2018 06:27:00 GMT+0900 (Korean Standard Time)
This can lead to errors where the date returned is off by many hours. To avoid this, pass in a time zone along with the string:
这可能会导致错误,因为返回的日期要过多个小时。 为避免这种情况,请在时区中输入以下字符串:
const exactBirthdate = new Date('6/13/2018 06:27:00 GMT-1000');
console.log(exactBirthdate) // Thu Jun 14 2018 01:27:00 GMT+0900 (Korean Standard Time)
/*
These formats also work:
new Date('6/13/2018 06:27:00 GMT-10:00');
new Date('6/13/2018 06:27:00 -1000');
new Date('6/13/2018 06:27:00 -10:00');
*/
You can also pass some, but not all, time zone codes:
您还可以传递一些但不是全部的时区代码:
const exactBirthdate = new Date('6/13/2018 06:27:00 PDT');
console.log(exactBirthdate) // Thu Jun 14 2018 01:27:00 GMT+0900 (Korean Standard Time)
Date
对象方法 (Date
Object Methods)Often you will not need the entire date, but just part of it like the day, week or month. Fortunately there are a number of methods to do just that:
通常,您不需要整个日期,而只需要一部分日期,例如日,周或月。 幸运的是,有许多方法可以做到这一点:
const birthday = new Date('6/13/2018 06:27:39');
birthday.getMonth() // 5 (0 is January)
birthday.getDate() // 13
birthday.getDay() // 3 (0 is Sunday)
birthday.getFullYear() // 2018
birthday.getTime() // 1528838859000 (milliseconds since the Unix Epoch)
birthday.getHours() // 6
birthday.getMinutes() // 27
birthday.getSeconds() // 39
birthday.getTimezoneOffset() // -540 (time zone offset in minutes based on your browser's location)
Getting dates and times right is no small task. Every country seems to have a different way of formatting dates, and accounting for different time zones and daylight savings/summer time takes, well, a whole lot of time. That's where Moment.js shines – it makes parsing, formatting, and displaying dates a breeze.
正确安排日期和时间并非易事。 每个国家/地区似乎都采用不同的日期格式,并且考虑到不同的时区和夏时制/夏令时需要花费大量时间。 这就是Moment.js的亮点-它使解析,格式化和显示日期变得轻而易举。
To start using Moment.js, install it through a package manager like npm
, or add it to your site through a CDN. See the Moment.js documentation for more details.
要开始使用Moment.js,请通过npm
类的包管理器进行安装,或通过CDN将其添加到您的站点中。 有关更多详细信息,请参见Moment.js文档 。
const now = moment();
This returns an object with the date and time based on your browser's location, along with other locale information. It's similar to native JavaScript's new Date()
.
这将返回一个具有日期和时间的对象,该日期和时间基于浏览器的位置以及其他语言环境信息。 它类似于本机JavaScript的new Date()
。
Similar to new Date(ms)
, you can pass the number of milliseconds since the epoch to moment()
:
类似于new Date(ms)
,您可以将自纪元以来的毫秒数传递给moment()
:
const dayAfterEpoch = moment(86400000);
If you want to get a date using a Unix timestamp in seconds, you can use the unix()
method:
如果要使用以秒为单位的Unix时间戳获取日期,可以使用unix()
方法:
const dayAfterEpoch = moment.unix(86400);
Parsing a date from a string with Moment.js is easy, and the library accepts strings in the ISO 8601 or RFC 2822 Date Time format, along with any string accepted by the JavaScript Date
object.
使用Moment.js从字符串中解析日期很容易,并且库接受ISO 8601或RFC 2822 Date Time格式的字符串,以及JavaScript Date
对象接受的任何字符串。
ISO 8601 strings are recommended since it is a widely accepted format. Here are some examples:
推荐使用ISO 8601字符串,因为它是一种广泛接受的格式。 这里有些例子:
moment('2019-04-21');
moment('2019-04-21T05:30');
moment('2019-04-21 05:30');
moment('20190421');
moment('20190421T0530');
Up until now, we have been using Moment.js in local mode, meaning that any input is assumed to be a local date or time. This is similar to how the native JavaScript Date
object works:
到目前为止,我们一直在本地模式下使用Moment.js,这意味着任何输入均假定为本地日期或时间。 这类似于本地JavaScript Date
对象的工作方式:
const exactBirthMoment = moment('2018-06-13 06:27:00');
console.log(exactBirthMoment) // Wed Jun 13 2018 06:27:00 GMT+0900 (Korean Standard Time)
However, to set a time zone, you must first get the Moment object in UTC mode:
但是,要设置时区,您必须首先以UTC模式获取Moment对象:
const exactBirthMoment = moment.utc('2018-06-13 06:27:00');
console.log(exactBirthMoment) // Wed Jun 13 2018 15:27:00 GMT+0900 (Korean Standard Time)
Then you can adjust for the difference in time zones with the utcOffset()
method:
然后,您可以使用utcOffset()
方法调整时区的差异:
const exactBirthMoment = moment.utc('2018-06-13 06:27:00').utcOffset('+10:00');
console.log(exactBirthMoment) // Wed Jun 13 2018 06:27:00 GMT+0900 (Korean Standard Time)
You can also set the UTC offset as a number or a string:
您还可以将UTC偏移量设置为数字或字符串:
moment.utc().utcOffset(10) // Number of hours offset
moment.utc().utcOffset(600) // Number of minutes offset
moment.utc().utcOffset('+10:00') // Number of hours offset as a string
To use named time zones (America/Los_Angeles
) or time zone codes (PDT
) with Moment objects, check out the Moment Timezone library.
要将命名时区( America/Los_Angeles
)或时区代码( PDT
)与Moment对象一起使用,请签出Moment时区库。
One of the major strengths that Moment.js has over native JavaScript Date
objects is how easy it is to format the output date and time. Just chain the format()
method to a Moment date object and pass it a format string as a parameter:
Moment.js相对于本机JavaScript Date
对象的主要优势之一是格式化输出日期和时间很容易。 只需将format()
方法链接到Moment日期对象,然后将格式字符串作为参数传递给它:
moment().format('MM-DD-YY'); // "08-13-19"
moment().format('MM-DD-YYYY'); // "08-13-2019"
moment().format('MM/DD/YYYY'); // "08/13/2019"
moment().format('MMM Do, YYYY') // "Aug 13th, 2019"
moment().format('ddd MMMM Do, YYYY HH:mm:ss') // "Tues August 13th, 2019 19:29:20"
moment().format('dddd, MMMM Do, YYYY -- hh:mm:ss A') // "Tuesday, August 13th, 2019 -- 07:31:02 PM"
Here's a table with some common formatting tokens:
这是带有一些常用格式标记的表:
Input | Output | Description |
---|---|---|
YYYY | 2019 | 4 digit year |
YY | 19 | 2 digit year |
MMMM | August | Full month name |
MMM | Aug | Abbreviated month name |
MM | 08 | 2 digit month |
M | 8 | 1 digit month |
DDD | 225 | Day of the year |
DD | 13 | Day of the month |
Do | 13th | Day of the month with ordinal |
dddd | Wednesday | Full day name |
ddd | Wed | Abbreviated day name |
HH | 17 | Hours in 24 hour time |
hh | 05 | Hours in 12 hour time |
mm | 32 | Minutes |
ss | 19 | Seconds |
a | am / pm | Ante or post meridiem |
A | AM / PM | Capitalized ante or post meridiem |
ZZ | +0900 | Timezone offset from UTC |
X | 1410715640.579 | Unix timestamp in seconds |
XX | 1410715640579 | Unix timestamp in milliseconds |
输入项 | 输出量 | 描述 |
---|---|---|
YYYY | 2019年 | 4位数的年份 |
YY | 19 | 2位数的年份 |
MMMM | 八月 | 月份全称 |
MMM | 八月 | 缩写的月份名称 |
MM | 08 | 2位数的月份 |
中号 | 8 | 1位数月 |
DDD | 225 | 一年中的一天 |
DD | 13 | 一个月中的某天 |
做 | 13日 | 每月第几天 |
dddd | 星期三 | 全天名称 |
ddd | 星期三 | 缩写的日期名称 |
H | 17 | 24小时制 |
h | 05 | 12小时制 |
毫米 | 32 | 分钟 |
ss | 19 | 秒 |
一个 | 上午下午 | 前或后子午线 |
一个 | 上午下午 | 大写的前或后子句 |
Z Z | +0900 | UTC时区偏移量 |
X | 1410715640.579 | Unix时间戳,以秒为单位 |
XX | 1410715640579 | Unix时间戳(以毫秒为单位) |
See the Moment.js docs for more formatting tokens.
有关更多格式标记,请参见Moment.js文档 。
Working with JavaScript Date
objects and Moment.js doesn't have to be time consuming. Now you should know more than enough to get started with both.
使用JavaScript Date
对象和Moment.js不必很费时。 现在,您应该已经足够了解这两个方面的知识。
翻译自: https://www.freecodecamp.org/news/the-ultimate-guide-to-javascript-date-and-moment-js/