Home>Article>Web Front-end> JavaScript date object Date (summary sharing)

JavaScript date object Date (summary sharing)

WBOY
WBOY forward
2022-06-27 13:48:57 2142browse

This article brings you relevant knowledge aboutjavascript, which mainly organizes issues related to the date object Date, including the creation of Date objects, methods of Date objects, etc., as follows Let's take a look, I hope it will be helpful to everyone.

JavaScript date object Date (summary sharing)

[Related recommendations:javascript video tutorial,web front-end

Date and time are programming processes Fortunately,JavaScripthas prepared a built-in object Date (date) for us. Through this object, we can create, store, modify, measure time, print and other basic operations. It is one of the required courses for everyJavaScriptprogrammer.

Creation of Date objects

Like ordinary objects, we can usenew Date()to create aDateobject, and we can also use Pass in some initialization parameters when creating.

new Date()

Creation case without parameters:

let now = new Date()console.log(now)

The code execution result is as follows:

JavaScript date object Date (summary sharing)

This simply outputs the specific time when the code is executed. What is displayed here is19:25 and 24 seconds on June 22, 2022.

new Date(milliseconds)

Creates a date object with millisecond parameters, wheremillisecondsrefers to the time since January 1, 1970 The number of milliseconds after UTC 0 (1 millisecond = 1/1000 seconds).

//创建一个时间,举例1970.1.1时间点0毫秒 let jan01_1970 = new Date(0) console.log(jan01_1970) //创建一个时间,比1970年1.1时间点晚3天(3天*24小时*3600秒*1000毫秒) let jan04_1970 = new Date(3 * 24 * 3600 * 1000) console.log(jan04_1970)

Code execution result:

JavaScript date object Date (summary sharing)

millisecondsis the time that has passed since 00:00:00 on January 1, 1970 The number of milliseconds, ortimestamp.

Time stamp is a simple digital representation of date. We usually usenew Date(milliseconds)to create a date. If we already have a dateDateobject, we can usedate.getTime()to get the timestamp corresponding to the date.

Note:

China is located in Zone 8, so the time in the above example is not 00:00:00, but 08:00:00

Time before 1970?

Time stamp is not only an integer, but also a negative number, for example:

//1969-12-31 00:00:00let dec31_1969 = new Date(-24 * 3600 * 1000)console.log(dec31_1969)

Code execution result:

JavaScript date object Date (summary sharing)

new Date(date_str )

If you use a timestamp for each creation time, it may not be convenient, because the timestamp calculation is still a bit difficult.

We can also use a time string to create a time, for example:

let date = new Date('2022-06-22 00:00:00')console.log(date)

Code execution result:

JavaScript date object Date (summary sharing)

new Date( year, month, date, hours, minutes, sec, ms)

  • year——Must be a four-digit number;
  • month——[0,11],0means January;
  • date——a certain day of the month, the default is1;
  • hours/minutes/sec/ms——The default is 0;

For example:

let date = new Date(2022,6,22,20,35,33)console.log(date)

Code execution result:

JavaScript date object Date (summary sharing)

We can also specify the number of milliseconds:

let date = new Date(2022,6,22,20,35,33,777)console.log(date)

Methods of the Date object

If we have aDateobject, we can get part of the time, such as year, month, date, etc., through the built-in method ofDateobject.

Get date content

For example we have datedate:

let date = new Date(2022,5,22,20,35,33)
  1. getFullYear()Get the year,date.getFullYear()Return2022;
  2. getMonth()Get the month,date.getMonth( )Return5, which is6month;
  3. getDate()Get the date of the current month,date.getDate ()Return22;
  4. getDay()Get the day of the week the current time is on,date.getDay()return3

Note:

  • 以上日期都是已于当地日期的,比如我这里是中国的时区
  • 获取年份一定要用getFullYeargetYear会返回两位数的年份

我们也可以获得0时区的时间,也就是UTC时间,分别对应getUTCFullYear()getUTCMonth()getUTCDay等。只需要在get后插入UTC即可。

举个例子:

let date = new Date(2022,5,22,20,35,33)console.log(date.getHours(),date.getUTCHours())

代码执行结果:

JavaScript date object Date (summary sharing)

夜里也可以看出,中国时区和0时区相差8小时。

  1. getTime()返回日期的时间戳,方法没有UTC模式;
  2. getTimezoneOffset()返回本地时区和0时区相差的时间,以分钟为单位,并且没有UTC模式;

设置日期内容

我们还可以通过Date对象的方法设置日期中的某一部分:

  • setFullYear(year, [month], [date])设置年份(月份、日)
  • setMonth(month, [date])设置月份(日)
  • setDate(date)设置日期(月份的第几天)
  • setHours(hour, [min], [sec], [ms])设置小时(分、秒、毫秒)
  • setMinutes(min, [sec], [ms])设置分钟(秒、毫秒)
  • setSeconds(sec, [ms])设置秒(毫秒)
  • setMilliseconds(ms)设置毫秒
  • setTime(milliseconds)(使用自1970-01-01 00:00:00 UTC+0以来的毫秒数来设置整个日期)

以上函数中只有setTime()没有UTC变体。

日期的自动校准

JavaScriptDate具备自动校准功能,这为我们针对时间的计算提供了极大的方便。

例如:

let date = new Date(2022,5,38)//注意这里的38console.log(date)

代码的执行结果:

屏幕截图 2022-06-23 185419

从执行结果我们可以看出"2022年6月38号"并没有使程序出现错误,而是将日期转成了”2022年7月8号“。

以上案例验证了,在JavaScript中,超出范围的日期会被Date对象自动分配。这样我们就可以非常方便的使用Date对象进行日期的计算。

例如,我们可以在日期上对年、月、日进行加减法运算:

let date = new Date(2022,5,23)//当前时间是2022-6-23date.setDate(date.getDate() + 8)//计算八天后的时间console.log(date)

代码执行结果:

JavaScript date object Date (summary sharing)

同样的,我们也可以使用date.setSeconds()方法已秒为单位计算日期。

日期转为数字、日期差值

日期Date转为数字的结果和使用date.getTime()的返回值相同,都是毫秒为单位的数值:

let date = new Date()console.log(+date)

代码执行结果:

JavaScript date object Date (summary sharing)

既然时间的本质就是数字,我们也可以进行时间差计算,并且以ms(毫秒)为单位。

例如:

let date1 = new Date(2022,5,23)let date2 = new Date(2022,5,24)console.log(`时间差为${date2-date1}ms`)

代码执行结果为:

JavaScript date object Date (summary sharing)

Date.now()

如果我们希望获得当前时间,更优的做法是使用Date.now()方法。这个方法会返回当前时间的时间戳,同时不需要创建额外的Date对象,这对内存开销、垃圾回收都是有好处的,而且代码更简洁。

举个栗子:

let begin = Date.now()for(let i = 1;i

代码执行结果:

JavaScript date object Date (summary sharing)

Date.parse()

Date.parse()方法可以读取一个日期字符串,并转为时间戳,但是字符串必须遵守一定的规则:YYYY-MM-DDTHH:mm:ss.sssZ

  • YYYY-MM-DD对应年-月-日
  • T属于分隔符
  • HH:mm:ss.sss对应时:分:秒.毫秒
  • Z可以是+-hh:mm格式的时区。单个字符Z表示UTC+0

字符串可以使用省略写法,例如:YYYY-MM-DDYYYY-MMYYYY

举个小李子:

let ms = Date.parse('2022-06-23T19:38:30.777+08:00')//时间戳let date = new Date(ms)console.log(date)

代码执行结果:

JavaScript date object Date (summary sharing)

Summary

  1. JavaScriptUseDateobject to process time:new Date();
  2. Month Calculating from 0
  3. Datehas many practical methods, we can get a certain period of time;
  4. Dateobject will be automatically calibrated, We can add and subtract dates directly;
  5. Date.now()can efficiently obtain the current time;

[Related recommendations:javascript video tutorialweb front-end

The above is the detailed content of JavaScript date object Date (summary sharing). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete