JavaScript date object Date (summary sharing)
This article brings you relevant knowledge about javascript, 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.
[Related recommendations: javascript video tutorial, web front-end】
Date and time are programming processes Fortunately, JavaScript
has 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 every JavaScript
programmer.
Creation of Date objects
Like ordinary objects, we can use new Date()
to create a Date
object, 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:
This simply outputs the specific time when the code is executed. What is displayed here is 19:25 and 24 seconds on June 22, 2022
.
new Date(milliseconds)
Creates a date object with millisecond parameters, where milliseconds
refers 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:
milliseconds
is the time that has passed since 00:00:00 on January 1, 1970 The number of milliseconds, or timestamp.
Time stamp is a simple digital representation of date. We usually use new Date(milliseconds)
to create a date. If we already have a date Date
object, we can use date.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:
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:
new Date( year, month, date, hours, minutes, sec, ms)
-
year
——Must be a four-digit number; -
month
——[0,11]
,0
means January; - date——a certain day of the month, the default is
1
; -
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:
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 a Date
object, we can get part of the time, such as year, month, date, etc., through the built-in method of Date
object.
Get date content
For example we have datedate
:
let date = new Date(2022,5,22,20,35,33)
-
getFullYear()
Get the year,date.getFullYear()
Return2022
; -
getMonth()
Get the month,date.getMonth( )
Return5
, which is6
month; -
getDate()
Get the date of the current month,date.getDate ()
Return22
; -
getDay()
Get the day of the week the current time is on,date.getDay()
return3
;
Note:
- 以上日期都是已于当地日期的,比如我这里是中国的时区
- 获取年份一定要用
getFullYear
,getYear
会返回两位数的年份
我们也可以获得0
时区的时间,也就是UTC
时间,分别对应getUTCFullYear()
、getUTCMonth()
,getUTCDay
等。只需要在get
后插入UTC
即可。
举个例子:
let date = new Date(2022,5,22,20,35,33)console.log(date.getHours(),date.getUTCHours())
代码执行结果:
夜里也可以看出,中国时区和0
时区相差8
小时。
-
getTime()
返回日期的时间戳,方法没有UTC
模式; -
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
变体。
日期的自动校准
JavaScript
的Date
具备自动校准功能,这为我们针对时间的计算提供了极大的方便。
例如:
let date = new Date(2022,5,38)//注意这里的38console.log(date)
代码的执行结果:
从执行结果我们可以看出"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)
代码执行结果:
同样的,我们也可以使用date.setSeconds()
方法已秒为单位计算日期。
日期转为数字、日期差值
日期Date
转为数字的结果和使用date.getTime()
的返回值相同,都是毫秒为单位的数值:
let date = new Date()console.log(+date)
代码执行结果:
既然时间的本质就是数字,我们也可以进行时间差计算,并且以ms
(毫秒)为单位。
例如:
let date1 = new Date(2022,5,23)let date2 = new Date(2022,5,24)console.log(`时间差为${date2-date1}ms`)
代码执行结果为:
Date.now()
如果我们希望获得当前时间,更优的做法是使用Date.now()
方法。这个方法会返回当前时间的时间戳,同时不需要创建额外的Date
对象,这对内存开销、垃圾回收都是有好处的,而且代码更简洁。
举个栗子:
let begin = Date.now()for(let i = 1;i<p>代码执行结果:</p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/067/2e91502ffdbd23d1af26c248feabbead-11.png" class="lazy" alt="JavaScript date object Date (summary sharing)"></p><h3 id="Date-parse">Date.parse()</h3><p><code>Date.parse()</code>方法可以读取一个日期字符串,并转为时间戳,但是字符串必须遵守一定的规则:<code>YYYY-MM-DDTHH:mm:ss.sssZ</code>。</p>
-
YYYY-MM-DD
对应年-月-日
-
T
属于分隔符 -
HH:mm:ss.sss
对应时:分:秒.毫秒
-
Z
可以是+-hh:mm
格式的时区。单个字符Z
表示UTC+0
字符串可以使用省略写法,例如:YYYY-MM-DD
、YYYY-MM
、YYYY
。
举个小李子:
let ms = Date.parse('2022-06-23T19:38:30.777+08:00')//时间戳let date = new Date(ms)console.log(date)
代码执行结果:
Summary
-
JavaScript
UseDate
object to process time:new Date()
; - Month Calculating from 0
-
Date
has many practical methods, we can get a certain period of time; -
Date
object will be automatically calibrated, We can add and subtract dates directly; -
Date.now()
can efficiently obtain the current time;
[Related recommendations: javascript video tutorial、web 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
