Translator: Front-end wisdom

Original text: css-tricks.com/everything-…

Click “like” and then look, wechat search [Big Move the world] pay attention to this person without dACHang background, but with a positive attitude upward. In this paper, making github.com/qq449245884… Has been included, the article has been categorized, also organized a lot of my documentation, and tutorial materials.

Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.

Date in JS is weird. When dealing with dates and times is tricky, we often resort to libraries like date-fns and Moment.

But we don’t always need to use libraries. Dates can actually be very simple if you know to pay attention to some always. All the information about Date objects follows

The time zone

Our world has hundreds of time zones. In JavaScript, we only care about two, local time and Coordinated Universal Time (UTC).

  • Local time is the time zone in which your computer is located.

  • UTC is actually a synonym for Greenwich Mean Time (GMT)

By default, almost every date method in JS except one is local time. The UTC time can be obtained only if UTC is specified.

Creation date

You can use new Date() to create a Date. There are four common ways to pass in parameters:

  1. Use the date string argument
  2. Use a series of parameters
  3. Timestamp parameter
  4. With no arguments

Use the date string argument

new Date('1988-03-21')
Copy the code

This way is convenient and intuitive.

If we write 21-03-1988 now, we can easily say March 21, 1988. But if you write 21-03-1988 in JS, you get an invalid date.

There’s a reason for that.

Date strings are interpreted differently in different parts of the world. For example, 11-06-2019 is June 11, 2019 or November 6, 2019. You can’t be sure which one I’m referring to unless you know the date system I’m using.

In JS, if you want to use date string arguments, you need to use globally accepted formats, one of which is the ISO 8601 extended format.

// ISO 8601 Extended format
`YYYY-MM-DDTHH:mm:ss:sssZ`
Copy the code
  • YYYY: 4-digit year
  • MM: double-digit months (January: 01, December: 12)
  • DD: two-digit date (0 to 31)
  • -: Date separator
  • T: indicates the start time
  • HH: 24 bit hours (0 to 23)
  • mm: minutes (0 to 59)
  • ss: seconds (0 to 59)
  • sss: milliseconds (0 to 999)
  • :: Time delimiter
  • Z: If presentZ, the date will be set to UTC, ifZIf no, it is the local time.

Hours, minutes, seconds, and milliseconds are optional. If you want to create a date for June 11, 2019, you can write it like this:

new Date('2019-06-11')    
Copy the code

Note here that creating a date using the date string argument is problematic, and you can find the problem by printing out the date you created.

If you live in an area after ** Greenwich Mean Time (GMT), you’ll get a date on June 10.

If you live in an area earlier than Greenwich Mean time, you have to wait for the date of June 11.

This happens because the method of the date string argument has special behavior: if you create a date (no time is specified), you get the date in UTC format.

In the scenario above, when the new Date(‘2019-06-11’) is used to create the Date, the Date is actually created on June 11, 2019, at 12 am UTC. That’s why people who live in areas after GMT get June 10 instead of June 11.

If you want to create a date in Local Time using the date string argument method, you need to include the time. If time is included, at least HH and mm need to be written

new Date('2019-06-11T00:00')  
Copy the code

The local time created with the date string argument compared to UTC can be a hard-to-catch error. Therefore, it is recommended not to use date strings to create date modes.

Greenwich Mean time GMT

In the 17th century, Greenwich Observatory conducted celestial observations for the expansion of maritime supremacy. The Old Royal Observatory was established in 1675, and in 1884 it was decided that the meridian through Greenwich should be used as the longitude zero dividing the eastern and western hemispheres of the earth. A 24-hour clock on the wall at the entrance of the observatory shows the current Time. For the whole world, the Time set here is the reference point of global Time. Greenwich Mean Time is the global standard for setting Time, which is known as Greenwich Mean Time. G.M.T. for short), marked on a watch, means the watch has a dual time function, that is, it can display the time of home and another country at the same time.

Universal Coordinated Time (UTC)

GMT is used in most timetables, but UTC is used instead of GMT. What is UTC? In fact, UTC refers to Coordinated Universal Time. UTC is actuarial time based on mean solar time (Greenwich Mean Time), a new time scale corrected for the motion of the Earth’s axis, and international Atomic time measured in seconds. UTC is more accurate than GMT in terms of universal standard time. A leap second is issued by the International Earth Rotation Service in Paris to align UTC with the Earth’s rotation period. So UTC essentially emphasizes a more accurate world time standard than GMT, but for current watches, GMT and UTC are no different in function and precision.

Created using a series of parameters

Up to seven arguments can be passed to create a date/time.

  1. Year: 4-digit Year

  2. Month: a Month in a year (0-11)

  3. Day: indicates a Day (1-31) in a month. If omitted, the default value is 1.

  4. Hour: indicates the Hour in a day (0-23). If omitted, the value is 0 by default.

  5. Minutes: indicates the Minutes (0-59). If omitted, the default value is 0.

  6. Seconds: indicates the number of Seconds (0-59). If omitted, the default value is 0.

  7. Milliseconds: Milliseconds (0-999), if omitted, defaults to 0.

    // 11th June 2019, 5:23:59am, Local Time new Date(2019, 5, 11, 5, 23, 59)

Many developers use this approach less because it looks complicated, but it’s actually quite simple. You can remember from left to right: year, month, day, hour, minute, second, and millisecond.

For example, January === 0, February === 1, March === 2, and so on.

A few more events to get familiar with the use of multiple parameters

// 21st March 1988, 12am, Local Time.
new Date(1988, 2, 21)

// 25th December 2019, 8am, Local Time.
new Date(2019, 11, 25, 8)

// 6th November 2023, 2:20am, Local Time
new Date(2023, 10, 6, 2, 20)

// 11th June 2019, 5:23:59am, Local Time
new Date(2019, 5, 11, 5, 23, 59)
Copy the code

Note that dates created with arguments are in local time

Another advantage of using parameters is that there is no confusion between local time and UTC. If UTC time is required, create the UTC date this way:

// 11th June 2019, 12am, UTC.
new Date(Date.UTC(2019, 5, 11))
Copy the code

Use a timestamp to create a date

In JS, the timestamp is the number of milliseconds that have passed since January 1, 1970 (also known as Unix era time). In my experience, timestamps are rarely used to create dates, but are generally used to compare different dates or to format dates, as discussed below.

Creates a date without arguments

If you create a date without any parameters, the date is set to the current time (in local time).

new Date()
Copy the code

Summary a wave

  1. Use new Date() to create a Date
  2. There are four possible grammars:
  • Use string date values
  • Using a series of parameters
  • Use time stamps
  • With no arguments
  1. It is best not to use string date values to create dates
  2. It is best to create dates with a series of arguments
  3. Remember that the months start at zero

Formatting date

Most programming languages provide a formatting tool to create any date format you want. For example, in PHP, you can format date(“d M Y”) to a date like 23, January 2019.

But formatting dates in JS is not easy.

Native Date objects provide seven formatting methods, each of which gives you a specific value, and they are useless.

const date = new Date(2019, 0, 23, 17, 23, 42)
Copy the code
  1. ToString: format to “Wed Jan 23 2019 17:23:42 GMT+0800 (CST)”

  2. ToDateString: format to “Wed Jan 23 2019”

  3. ToLocaleString: format to “2019/1/23 5:23:42 PM”

  4. ToLocaleDateString: format to “2019/1/23”

  5. ToGMTString: formatted to “Wed, 23 Jan 2019 09:23:42 GMT”

  6. ToUTCString: formatted to “Wed, 23 Jan 2019 09:23:42 GMT”

  7. ToISOString: format to “2019-01-23T09:23:42.000z”

If you need a custom format, create it yourself.

Write custom date formats

Imagine a date format like Thursday, January 23, 2019. You need to know the Date object Date method.

To get such a format, use the four methods in Date:

  1. GetFullYear: Gets the 4-digit local time year

  2. GetMonth: gets the month of the time. The value starts from 0

  3. GetDate: get a day in a month (1-31)

  4. GetDay: Gets the day of the week (0-6) of the local time, starting on Sunday (0) and ending on Saturday (6).

    const d = new Date(2019, 0, 23) const year = d.getFullYear() // 2019 const date = d.getDate() // 23

Since weeks and months start at 0, we can create a mapping table:

Const up = {0: 'in January, 1:' in February, 2: 'march, 3:' in April, 4: 'may' 5: 'June, 6:' July, 7: 'August', 8: 'September', 9: 'in October, 10: 'November ', 11:' December '}Copy the code

Since the months start at 0, we can use arrays instead of objects to get the same result:

Const up = [' in January, February, march, April, 'may' and 'June', 'July', 'August', 'September', 'October', 'November', 'December'}Copy the code

To get January, you need

Const monthIndex = d.goetmonth () const monthName = months[monthIndex] console.log(monthName) // 1 monthCopy the code

To simplify:

Const monthName = months(d.goetmonth ()) console.log(monthName) // 1 monthCopy the code

To get Thursdays, do the same thing:

Const days = [' on Sunday, Monday, Tuesday, Wednesday, ' ', 'on Thursday, Friday, Saturday']Copy the code

Obtaining method:

Const dayName = days[d.gettday ()] // ThursdayCopy the code

And then they put it together. It’s relatively tedious.

If you need to create custom format times, you can use the following methods

  1. GetHours: Obtains the local time obtains the hours (0-23).

  2. GetMinutes: obtains the local time. The value ranges from 0 to 59.

  3. GetSeconds: obtain the local time number of seconds (0-59).

  4. GetMilliseconds: Gets the local time in milliseconds (0-999).

Comparison of dates

To compare before and after dates, use the >, <, >= and <= lines.

const earlier = new Date(2019, 0, 26)
const later = new Date(2019, 0, 27)

console.log(earlier < later) // true
Copy the code

It is troublesome to compare two dates to see if they are the same or not. You can’t use == or === directly

const a = new Date(2019, 0, 26)
const b = new Date(2019, 0, 26)

console.log(a == b) // false
console.log(a === b) // false
Copy the code

You can get their timestamps by getTime and compare them with timestamps.

const isSameTime = (a, b) => {
  return a.getTime() === b.getTime()
}

const a = new Date(2019, 0, 26)
const b = new Date(2019, 0, 26)
console.log(isSameTime(a, b)) // true
Copy the code

If you just want to check whether two dates are on the same day, compare their getFullYear, getMonth, and getDate values.

const isSameDay = (a, b) => {
  return a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate()=== b.getDate()
}

const a = new Date(2019, 0, 26, 10) // 26 Jan 2019, 10am
const b = new Date(2019, 0, 26, 12) // 26 Jan 2019, 12pm
console.log(isSameDay(a, b)) // true
Copy the code

Gets a date from another date

There are two possible situations where you want to get a date from another date.

  1. Sets another date-specific date/time value
  2. Add/subtract the increment from another date

Sets another date-specific date/time value

You can set the date/time of another date using the following methods:

  1. setFullYear: Set year
  2. setMonth: Set month
  3. setDate: Specifies a day in a month
  4. setHours: set when
  5. setMinutes: set points
  6. setSeconds: set up the second
  7. setMilliseconds: set milliseconds

For example, if you want to set the date to the 15th of each month, you can use setDate(15)

const d = new Date(2019, 0, 10)
d.setDate(15)

console.log(d) // 15 January 2019
Copy the code

Note: The setter method above changes the original date object. In practice, we should not change the object; we should perform these operations on the new date object.

const d = new Date(2019, 0, 10)
const newDate = new Date(d)
newDate.setMonth(5)

console.log(d) // 10 January 2019
console.log(newDate) // 10 June 2019
Copy the code

Add/subtract the increment from another date

There are two general ways to add/subtract deltas. The first approach, which is more popular on Stack Overflow, is concise but harder to master. The second method is more verbose, but easier to understand.

Suppose you want a date three days from today. For this example, assume that today is March 28, 2019.

The first way

const today = new Date(2019, 2, 28)
Copy the code

First, we create a new Date object so that we don’t change the original Date

const finalDate = new Date(today)
Copy the code

Next, we need to know the value to change. Since we want to change the date, we can use getDate to get the date

const currentDate = today.getDate()
Copy the code

Because we get the date three days from now, we need to add 3 to the date we get

setDate(currentDate + 3)
Copy the code

Complete code:

const today = new Date(2019, 2, 28)
const finalDate = new Date(today)
finalDate.setDate(today.getDate() + 3)

console.log(finalDate) // 31 March 2019
Copy the code

The second way

Using the getFullYear, getMonth, getDate methods, we change the corresponding values, and then we create the final Date using new Date.

const today = new Date(2019, 2, 28)

// Getting required values
const year = today.getFullYear()
const month = today.getMonh()
const day = today.getDate()

// Creating a new Date (with the delta)
const finalDate = new Date(year, month, day + 3)

console.log(finalDate) // 31 March 2019
Copy the code

Automatic date correction

If you give Date a value outside its acceptable range, JS will automatically recalculate the Date.

As shown below, assuming we set the date on March 33, 2019 and there is no 33 in the calendar, JS will automatically change March 33 to April 2.

This means you don’t have to worry about counting minutes, hours, days, months, etc. when creating deltas, JavaScript takes care of it automatically.

The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.