search
HomeWeb Front-endJS TutorialJavaScript 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.

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)

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)

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)

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], 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:

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

代码执行结果:

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<p>代码执行结果:</p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/067/2e91502ffdbd23d1af26c248feabbead-11.png?x-oss-process=image/resize,p_40" 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-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. 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
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools