Ласкаво просимо до нашого остаточного посібника з Date
об’єкта JavaScript та Moment.js. Цей підручник навчить вас усьому, що вам потрібно знати про роботу з датами та часом у ваших проектах.
Як створити Date
об'єкт
Отримайте поточну дату та час
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)
Синтаксис є Date(year, month, day, hour, minute, second, millisecond)
.
Зверніть увагу, що місяці мають нульовий показник, починаючи з січня о 0 і закінчуючи груднем о 11.
Отримайте дату та час із позначки часу
const unixEpoch = new Date(0);
Це представляє час у четвер, 1 січня 1970 р. (UTC), або час епохи Unix. Unix Epoch є важливим, оскільки це те, що JavaScript, Python, PHP та інші мови та системи використовують внутрішньо для обчислення поточного часу.
new Date(ms)
повертає дату епохи плюс кількість пропущених мілісекунд. За день існує 86 400 000 мілісекунд, отже:
const dayAfterEpoch = new Date(86400000);
повернеться в п’ятницю, 2 січня 1970 р. (UTC).
Отримайте дату та час із рядка
const stringDate = new Date('May 29, 2019 15:00:00'); // Wed May 29 2019 15:00:00 GMT-0400 (Eastern Daylight Time)
Отримати дату таким чином дуже гнучко. Усі наведені нижче приклади повертають дійсні 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')
Ви також можете використовувати Date.parse()
метод, щоб повернути кількість мілісекунд з епохи (1 січня 1970 року):
Date.parse('1970-01-02') // 86400000 Date.parse('6/16/2019') // 1560610800000
Встановлення часового поясу
При передачі рядка дати без встановлення часового поясу 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)
Це може призвести до помилок, коли дата повернення вимикається на багато годин. Щоб цього уникнути, передайте часовий пояс разом із рядком:
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'); */
Ви також можете передати деякі, але не всі коди часових поясів:
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
Об’єктні методи
Часто вам знадобиться не вся дата, а лише частина її, наприклад день, тиждень або місяць. На щастя, існує безліч методів, як це зробити:
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)
Зробіть роботу з датами простішою за допомогою Moment.js
Правильно визначити дати та час - це не мале завдання. Здається, кожна країна має різний спосіб форматування дат, а облік різних часових поясів та переходу на літній час / літній час займає багато часу. Ось де сяє Moment.js - він робить синтаксичний аналіз, форматування та відображення дат легким.
Щоб почати використовувати Moment.js, встановіть його через менеджер пакетів, наприклад npm
, або додайте на свій сайт через CDN. Докладніше див. У документації Moment.js.
Отримайте поточну дату та час за допомогою Moment.js
const now = moment();
Це повертає об’єкт із датою та часом на основі місцезнаходження вашого браузера, а також іншу інформацію про локаль. Це схоже на власний JavaScript new Date()
.
Отримайте дату та час із позначки часу за допомогою Moment.js
Подібно до new Date(ms)
, ви можете передати кількість мілісекунд з епохи до moment()
:
const dayAfterEpoch = moment(86400000);
Якщо ви хочете отримати дату за допомогою мітки часу Unix за лічені секунди, ви можете скористатися unix()
методом:
const dayAfterEpoch = moment.unix(86400);
Отримайте дату та час із рядка за допомогою Moment.js
Проаналізувати дату з рядка за допомогою Moment.js досить просто, і бібліотека приймає рядки у форматі ISO 8601 або RFC 2822 Date Time, а також будь-який рядок, прийнятий Date
об’єктом JavaScript .
Рядки ISO 8601 рекомендуються, оскільки це широко прийнятий формат. Ось кілька прикладів:
moment('2019-04-21'); moment('2019-04-21T05:30'); moment('2019-04-21 05:30'); moment('20190421'); moment('20190421T0530');
Встановлення часового поясу за допомогою Moment.js
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:
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:
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:
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:
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.
Format the date and time with Moment.js
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().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 |
See the Moment.js docs for more formatting tokens.
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.