Table of Contents
Creation of Date objects
new Date()
new Date(milliseconds)
Time before 1970?
new Date(date_str )
new Date( year, month, date, hours, minutes, sec, ms)
Methods of the Date object
Get date content
设置日期内容
日期的自动校准
日期转为数字、日期差值
Date.now()
Date.parse()
Summary
Home Web Front-end JS Tutorial JavaScript date object Date (summary sharing)

JavaScript date object Date (summary sharing)

Jun 27, 2022 pm 01:48 PM
javascript

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.

JavaScript date object Date (summary sharing)

[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)
Copy after login

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 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)
Copy after login

Code execution result:

JavaScript date object Date (summary sharing)

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)
Copy after login

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)
Copy after login

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], 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)
Copy after login

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)
Copy after login

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)
Copy after login
  1. getFullYear()Get the year, date.getFullYear()Return 2022;
  2. getMonth()Get the month, date.getMonth( )Return 5, which is 6 month;
  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()return 3

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())
Copy after login

代码执行结果:

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)
Copy after login

代码的执行结果:

屏幕截图 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)
Copy after login

代码执行结果:

JavaScript date object Date (summary sharing)

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

日期转为数字、日期差值

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

let date = new Date()console.log(+date)
Copy after login

代码执行结果:

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`)
Copy after login

代码执行结果为:

JavaScript date object Date (summary sharing)

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>
Copy after login
  • 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)
Copy after login

代码执行结果:

JavaScript date object Date (summary sharing)

Summary

  1. JavaScriptUse Date object to process time: new Date();
  2. Month Calculating from 0
  3. Date has many practical methods, we can get a certain period of time;
  4. Date object 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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

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

See all articles