[js] knowledge about time and date and some processing!

preface

Some things seem insignificant, but in real development, they will make you a big stumbling block. For example, time processing in js is not a big problem, but it will take some time every time, so I plan to take advantage of the weekend to sort out the knowledge about time and date in js.

1, Some concepts

1. 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 where your computer is located.
  • UTC is actually synonymous with Greenwich mean time (GMT)

By default, almost every date method (except one) in JS is local time. UTC time can only be obtained by specifying UTC.

2. Date object

ECMAScript's Date type is a reference type. A reference type is a structure that organizes data and functions together. It sounds like a class, but it's not.

js Although it is an object-oriented language, but ECMAScript It lacks some basic structures of traditional object-oriented programming languages, including classes and interfaces.
Reference types are sometimes called object definitions because they describe the properties and methods of their own objects. 

The Date type saves the Date as the number of milliseconds that have elapsed since midnight (0:00) coordinated universal time (UTC) on January 1, 1970.

To create a date object, use the new operator to call the Date() constructor:
let now = new Date()

2, Creation date

Without passing parameters to the Date constructor, the created object will save the current Date and time.

const date = new Date()
console.log(date)	//	Sun Sep 12 2021 10:14:58 GMT+0800 (China standard time)

To create a date object based on another date and time, you must pass in its millisecond representation (the number of milliseconds after midnight on January 1, 1970, UNIX era).
There are three common ways to pass in parameters:

  1. Use date string parameter
  2. Use a series of parameters
  3. Timestamp parameters

1. Use date string parameters:

- Date string must be in the format *year-month-day*,Also note that it must be a string ha;
- If the format is not *year-month-day*,Will report the wrong time information or directly report the error, because you can't be sure which one I mean, unless you know the date system I'm using.
- If it is not a string, there will also be a problem. It may directly return the midnight time on January 1, 1970
const date2 = new Date('2021-09-12')
console.log(date2)	//	Sun Sep 12 2021 08:00:00 GMT+0800 (China standard time) 	 Correct expression √
const date3 = new Date(2021-09-12)
console.log(date3)	//	Thu Jan 01 1970 08:00:02 GMT+0800 (China standard time) 	 Wrong
const date4 = new Date('12-09-2021')
console.log(date4)	//	Thu Dec 09 2021 00:00:00 GMT+0800 (China standard time) 	 Wrong

In js, if you want to use the date string parameter, you need to use a globally acceptable format, one of which is the ISO8601 extended format

// ISO 8601 Extended format
`YYYY-MM-DDTHH:mm:ss:sssZ`
  • YYYY: 4-digit year
  • MM: two digit month (i.e. 01 in January and 12 in December)
  • 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 separator
  • Z: If Z exists, the date will be set to UTC; if Z does not exist, it will be local time.

Hours, minutes, seconds and milliseconds are optional, just like date2 above.
However, if you only specify the date and do not specify the time after T, you will get the date set in UTC format
If you want to create a date in local time using the date string parameter method, you need to include the time. If time is included, at least HH and mm need to be written

//	At 0:00 on September 12, Greenwich, it's 8:00 a.m. in Beijing time
console.log(date2)	//	Sun Sep 12 2021 08:00:00 GMT+0800 (China standard time)
//	But given the time, it will honestly display the local time
const date5 = new Date('2021-09-12T00:00')
console.log(date5)	//	Sun Sep 12 2021 00:00:00 GMT+0800 (China standard time)

Summary: the comparison of local time and UTC created with date string parameters may be a hard to catch error. Therefore, it is not recommended to use date strings to create date methods.
It's not recommended that we use this way. What way?

2. Use a series of parameters:

You can pass in up to seven parameters to create a date / time

  • Year: 4-digit year

  • Month: a month of the year (0-11)

  • Day: the day of each month (1-31). If omitted, it defaults to 1

  • Hour: hour of the day (0-23)

  • Minutes: minutes (0-59). If omitted, it defaults to 0

  • Seconds: seconds (0-59). If omitted, it defaults to 0

  • Milliseconds: milliseconds (0-999). If omitted, it defaults to 0
    Many developers rarely use this method because it looks complex, but it is actually very simple. You can remember from left to right: year, month, day, hour, minute, second and millisecond.

      One important point to note: Month It started from 0!
    

For example:

// 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)
Note that the dates created with the parameters are local time
 Another advantage of using parameters is that they will not be used at local time and UTC Confusion between, if necessary UTC Time, please create it this way UTC Date:
// 11th June 2019, 12am, UTC.
new Date(Date.UTC(2019, 5, 11))

3. Use timestamp to create date:

In JS, the timestamp is the number of milliseconds since January 1, 1970 (also known as Unix era time on January 1, 1970). According to Daniel's experience, time stamps are rarely used to create dates. Generally, time stamps are used to compare different dates or format dates, which will be discussed later!

3, Format date

1. diss js first

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") into a date such as 231 month 2019.

But! Formatting dates in js is not easy.

The native Date object provides seven formatting methods, each of which will give you a specific value, and they are useless.

const date = new Date(2019, 0, 23, 17, 23, 42)
  1. toString: formatted as "Wed Jan 23 2019 17:23:42 GMT+0800 (China standard time)"
  2. toDateString: formatted as "Wed Jan 23 2019"
  3. toLocaleString: formatted as "5:23:42 PM, January 23, 2019"
  4. toLocaleDateString: formatted as "2019 / 1 / 23"
  5. toGMTString: formatted as "Wed, 23 Jan 2019 09:23:42 GMT"
  6. toUTCString: formatted as "Wed, 23 Jan 2019 09:23:42 GMT"
  7. ToString: formatted as "2019-01-23T09:23:42.000Z"

If you need to customize the format, you should create it yourself.

2. Write custom date format

Suppose you want a Date format like Thursday, January 23, 2019. You need to know the Date method of the Date object

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

  1. getFullYear: get the 4-digit year of local time
  2. getMonth: get the month of the current time. Note that it starts from 0
  3. getDate: get a day in the local time month (1-31)
  4. getDay: get the day of the week (0-6) of the local time. It starts on Sunday (0) and ends on Saturday (6).
const d = new Date(2019, 0, 23) 
const year = d.getFullYear() // 2019 
const date = d.getDate() // 23

In this way, we can create our own functions to process different business logic

A specific date and time processing function is posted below. This function should be able to meet a considerable part of business requirements.

/**
 * @param day Based on today, the next few days, exp: - 7 - the date 7 days ago; 5 - the date five days from today
 * @param opt timeType: 'local'-Adopt local time, specific to days; Timetype: do not fill in /'utc '- UTC time is adopted by default; timeType
 * @returns 
 */
export function getDay (day: number, opt?: any): String {
  //Date() returns the date and time of the current day.
  const days = new Date()
  //getTime() returns the number of milliseconds since January 1, 1970.
  const gettimes = days.getTime() + 1000 * 60 * 60 * 24 * day
  //setTime() sets the Date object in milliseconds.
  days.setTime(gettimes)
  const year = days.getFullYear()
  let month = days.getMonth()+1 as any
  if(month<10){
    month = "0" + month
  }
  let today = days.getDate() as any
  if(today<10){
    today="0"+today
  }
  if (opt && opt.timeType === 'local')  return `${year}-${month}-${today}T00:00`
  if ( !opt || (opt && opt.timeType === 'UTC') )return `${year}-${month}-${today}`
}

Tags: Javascript

Posted on Sat, 20 Nov 2021 09:23:59 -0500 by woozy