המדריך האולטימטיבי לתאריך JavaScript ו- Moment.js

ברוך הבא למדריך האולטימטיבי שלנו בנושא 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), או בזמן יוניקס אפוק. עידן יוניקס חשוב מכיוון שמשתמשים בו 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();

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

Get a date and time from a timestamp with Moment.js

Similar to new Date(ms), you can pass the number of milliseconds since the epoch to moment():

const dayAfterEpoch = moment(86400000);

If you want to get a date using a Unix timestamp in seconds, you can use the unix() method:

const dayAfterEpoch = moment.unix(86400);

Get a date and time from a string with Moment.js

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.

ISO 8601 strings are recommended since it is a widely accepted format. Here are some examples:

moment('2019-04-21'); moment('2019-04-21T05:30'); moment('2019-04-21 05:30'); moment('20190421'); moment('20190421T0530');

Setting a time zone with 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:

InputOutputDescription
YYYY20194 digit year
YY192 digit year
MMMMAugustFull month name
MMMAugAbbreviated month name
MM082 digit month
M81 digit month
DDD225Day of the year
DD13Day of the month
Do13thDay of the month with ordinal
ddddWednesdayFull day name
dddWedAbbreviated day name
HH17Hours in 24 hour time
hh05Hours in 12 hour time
mm32Minutes
ss19Seconds
aam / pmAnte or post meridiem
AAM / PMCapitalized ante or post meridiem
ZZ+0900Timezone offset from UTC
X1410715640.579Unix timestamp in seconds
XX1410715640579Unix 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.