“This is the fourth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

There are already plenty of useful time handlers, but sometimes you don’t want to introduce other plugins. In this case, you can directly use the built-in Date object of JS to handle time. Take a look below!


preface

πŸ‘‰ time processing plugin: moment.js practical operation/dayjs official documentation

πŸ‘‰ is added irregularly to……

DateObject method lookup table

Put it at the front for daily access πŸ€—

Key words: acquisition

methods describe
getFullYear() To obtainyearsShare (4 digits)
getMonth() To obtainmonthFraction (0 ~ 11).
getDate() To get amonthIn aday(1 ~ 31).
getHours() Get a smallwhenThe number ranges from 0 to 23.
getMinutes() To obtainpointsNumber of clocks (0 to 59).
getSeconds() To obtainsecondsThe value ranges from 0 to 59.
getMilliseconds() To obtainmsThe value ranges from 0 to 999.
getDay() To obtain aweeksIn aday(0 ~ 6).
getTime() Obtained between January 1, 1970msThe number.

🎨 Example:

let today = new Date();
today.getFullYear()
Copy the code


Key words: Setting

methods describe
setFullYear(year, [month], [date]) Is a date object based on local timeSet the date(4 digits)
setMonth(month, [date]) Is a date object based on local timeSet up in. (0 ~ 11).
setDate(date) Is a date object based on local timeSet the date. (1 ~ 31).
setHours(hour, [min], [sec], [ms]) Is a date object based on local timeSet hours. (0 ~ 23).
setMinutes(min, [sec], [ms]) Is a date object based on local timeSet the minutes. (0 ~ 59).
setSeconds(sec, [ms]) Is a date object based on local timeSet the number of seconds. (0 ~ 59).
setMilliseconds(ms) Is a date object based on local timeSetting milliseconds. (0 ~ 999).
setTime(milliseconds) Is a date object based on local timeSet a time. Between January 1, 1970msNumber)

🎨 Example:

let today = new Date(); today.setFullYear(2022); // The result is a timestampCopy the code

πŸ’₯ Note: The representation of brackets [] is optional, such as

dateObj.setFullYear(year, [month], [date])

  • Year: Specifies the integer value of the year, for example, 1995.
  • Month: An integer value between 0 and 11, from January to December.
  • Date: An integer value between 1 and 31, indicating the day of the month. If you specifydateParameters must be specified at the same timemonth.

If the month and date parameters are not specified, the return values of the getMonth and getDate methods are used.




create

There is no parameter

Date object with no arguments representing the current Date and time

let now = new Date()
Copy the code


A parameter

The argument can be a timestamp or a string

// let Jan02_1970 = new Date(24 * 3600 * 1000); // string let date = new date ("2021-11-04");Copy the code

The integer argument passed represents the number of milliseconds since 1970-01-01 00:00:00, which is called a timestamp.


Multiple parameters

Syntax: new Date(year, month, Date, hours, minutes, seconds, ms)

Creates a date with the given component in the current time zone. Only the first two parameters are required.

  • yearMust be a four-digit number:2013It’s legal,98It’s not legal.
  • monthCount from0(January) start, arrive11(December) end.
  • dateThe value is a specific day in the current month. If the value is missing, it is the default value1.
  • ifhours/minutes/seconds/msIf no, the default values are used0.

Year, month, day, hour, minute, and second are set or retrieved as follows




A practical method

Date.parse()

πŸ“– description: Parses a string representing a date and returns the number of milliseconds from 1970-1-1 00:00:00 UTC to the date object (the DATE object’s UTC time).

πŸ“– Format: The string format is yyyY-MM-DDTHh: MM: ss.sssz, where:

  • YYYY-MM-DD— Date: year – Month – day.
  • character"T"Is a delimiter.
  • HH:mm:ss.sss— Time: hours, minutes, seconds, milliseconds.
  • Optional characters'Z' δΈΊ +-hh:mmFormat time zone. A single characterZRepresents UTC+0 time zone.

Shorter forms are also acceptable, such as YYYY-MM-DD or YYYY-MM, or even YYYY.


Date.now()

πŸ“– Description: Returns the number of milliseconds since 00:00:00, January 1, 1970 (UTC) to the current time.


dateObj.toJSON()

πŸ“– Description: Returns a string in JSON format

let date = new Date(); Thu Nov 09 2017 18:54:04 GMT+0800 let jsonDate = (date).tojson (); //Thu Nov 09 2017 18:54:04 GMT+0800 let jsonDate = (date).tojson (); //" 2017-11-09T10:51:11.395z "let backToDate = new Date(jsonDate); //Thu Nov 09 2017 18:54:04 GMT+0800Copy the code


dateObj.valueOf()

πŸ“– Description: The number of milliseconds from 00:00:00:00 on January 1, 1970 to that date.




The practical application

Date to timestamp

let date = new Date('2021-11-04'); // let time = date.parse (Date); //1635984000000 // let time = date.valueof (); //1635984000000 // let time = date.gettime (); / / 1635984000000Copy the code


Get the time after

🎨 For example, obtain the time two days after the specified time

πŸ‡, obtain the date directly +2, change the date by setting the date. (The method of obtaining and setting can be found in the last reference table.)

let date = new Date(2021, 02, 01); date.setDate(date.getDate() + 2); Console. log(date) //Wed Mar 03 2021 00:00:00 GMT+0800 (Chinese Standard time)Copy the code


Get the previous time

🎨 for example: today is the 4th, the day before, it should be the 3rd

πŸ‡ Idea: Subtract the number of days from the current date

function getDateAgo(date, days) {
  let dateCopy = new Date(date);
  dateCopy.setDate(date.getDate() - days);
  return dateCopy.getDate();
}
Copy the code


Gets the last day of a month

πŸ’ Idea: Use the next month to create the date, pass zero as the day, because the date will be automatically adjusted. So when we pass 0, it means “the day before the first day of the month,” in other words: “the last day of the last month.”

function getLastDayOfMonth(year, month) {
  let date = new Date(year, month + 1, 0);
  return date.getDate();
}
Copy the code


Gets the number of days in the current month

πŸ‘ 提 η€Ί : The last day of this month is the number of days in the current month.

function mGetDate(month){ var date = new Date(); var year = date.getFullYear(); if(! month){ month = date.getMonth()+1; } var d = new Date(year, month, 0); return d.getDate(); }Copy the code

References:

Date and time

MDN Date


🎨 [thumbs up] [concerns] don’t get lost, more front-end dry goods waiting for you to unlock

Phase to recommend

πŸ‘‰ Do you really know JavaScript destruct assignment?

πŸ‘‰ super detailed SUMMARY of JS mapping (Map)

πŸ‘‰ illustrates JavaScript’s garbage collection mechanism

πŸ‘‰JavaScript this binding rule