search
HomeWeb Front-endJS TutorialComplete mastery of JavaScript's Date object

This article brings you relevant knowledge about javascript, which mainly introduces related issues about date objects. The Date object is a constructor, so we must go through object instantiation, that is It can only be used after passing new. Let’s take a look at it. I hope it will be helpful to everyone.

Complete mastery of JavaScript's Date object

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

Next, we will explain the second type of common built-in object in JS - Date object

#Date object is different from Math object. Math object is not a constructor and can be used directly. The Date object is a constructor, so we must instantiate the object, that is, before it can be used after passing new. The Date object is mostly used to deal with time and date issues in development.

Date object instantiation:

var date=new Date();

Date object instantiation can have parameters or no parameters. The output without parameters is the current system The standard time at that time, if there are parameters, we can output the time we want to display

1: Instantiation without parameters

It will be displayed after instantiation without parameters The time and date of the current system

var date=new Date();  //没有参数

console.log(date);  //会输出当前时间

2: Instantiation with parameters

Instantization with parameters is divided into two The two types are numeric type and string type . The following are examples of the two types respectively

1. Instantiation of numeric parameters:

var date=new Date(2021,1,18);  //数字型参数

console.log(date);

You can see that the parameter we input is January, but the output result is Feb (February). The numerical output will be smaller than the month we input. One month older.

2. Instantiation of string parameters:

var date=new Date('2021-1-18 12:56:00');  //字符串型参数

console.log(date);

The parameter is January, and the output result is also January. Therefore, string parameters are used more often than numeric parameters.

3: Formatting year, month and day

We already know that the Math object has many properties and methods that can be used directly, and the same is true for the Date object, which can also be used after instantiation There are many methods, and there are three commonly used methods to format the year, month and day

getFullYear() Output the current year

getMonth() Output the current month (It should be noted that the output month is 1 less than the actual month, and the output real month should be increased by 1)

getDate() Output the current day

##getDay() Output the current day of the week (Corresponding numbers from Monday to Sunday: 1 2 3 4 5 6 0)

var Date=new Date();

 console.log(Date.getFullYear());  //输出当前年份

 console.log(Date.getMonth() + 1);  //输出结果为当前月份的前一月,要手动加1才能返回当前月份

 console.log(Date.getDate());  //输出当前几号

 console.log(Date.getDay());  //输出当前周几

If you want the output effect to be

Tuesday, January 18, 2021, you can do the following

(because the day of the week can only return one number , but according to custom, what we want to return is the 'day of the week', so we treat the returned number as an index and put Sunday to Saturday into an array. Because Sunday returns 0, we put Sunday in the array. A position, corresponding to the 0 index)

var arr=['星期天','星期一','星期二','星期三','星期四','星期五','星期六'];

var Date=new Date();

var year=Date.getFullYear(); 

var month=Date.getMonth() + 1; 

var date=Date.getDate();

var day=Date.getDay();  

 console.log(year + '年' + month + '月' + date + '日' + arr[day]);

Four: Formatting hours, minutes and seconds

is the same as the above formatted year, month and day The usage is similar to

getHours() Output the current hour

getMinutes() Output the current minutes

getSeconds()    输出当前秒

var Date=new Date();  

console.log(Date.getHours());  //输出当前小时

console.log(Date.getMinutes());  //输出当前分钟

console.log(Date.getSeconds());  //输出当前秒

 

 输出连续格式时分秒:

将其封装在了函数内,并利用三元运算符将不足10的数字补0,符合平常看时间的习惯

function time()

{

var time=new Date();

var h=time.getHours();

h = h<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/067/ffba680ef6f1be060ab412959094bac2-6.png?x-oss-process=image/resize,p_40" class="lazy" alt=""    style="max-width:90%"  style="max-width:90%"></p><h3 id="strong-五-获取当前时间总毫秒数-时间戳-strong"><strong>五:获取当前时间总毫秒数(时间戳)</strong></h3><p>这里所说的总毫秒数是指当前时间距离1970年1月1日的总毫秒数,共有四种方法可以表示</p><p><span style="color:#be191c;"><strong>valueOf()</strong></span></p><p><span style="color:#be191c;"><strong>getTime()</strong></span></p><pre class="brush:php;toolbar:false">var date=new Date();

console.log(date.valueOf());   

console.log(date.getTime());

 或者使用另外一种简便写法 var date=+new Date();返回的就是总毫秒数

var date=+new Date();

console.log(date);

 以及H5新增加的一种方法,这个方法不需要实例化对象即可获得,更为简便

console.log(Date.now());

六:倒计时案例(重点)

在日常开发中很多地方都会用的到倒计时,例如淘宝,京东的双十一秒杀倒计时等,我们如何也写出一个倒计时效果呢,我们首先会想到刚才学到的获取当前时间,再减去我们设置好的时间即可,但是我们获取到的标准时间很可能会出现减去之后是负数的情况(例如02-12)这怎么办呢?于是我们的时间戳便有利用价值了,时间戳即刚才讲到过的总毫秒数,这个时间是永远不会重复的,对此我们可以使用设置好的总毫秒数减去当前的总毫秒数,在进行一系列单位换算,就可以得到一个简单的倒计时案例了,首先我们需要熟练记清楚单位换算之间的关系:

1秒=1000毫秒

天数=秒数/60/60/24

小时数=秒数/60/60%24

分钟数=秒数/60%60

秒数=秒数%60

对于无法整除的秒数,我们利用 parseInt() 方法取整即可,有了这样一个换算关系,我们就可以轻松地完成这个倒计时案例了

function count(time)

{

    var nowtime=+new Date(); //得到当前时间

    var aimtime=+new Date(time);  //得到目标时间(结束时间)

    var times=(aimtime-nowtime)/1000;  //得到倒计时时间差(毫秒) 除1000得到秒

    var d=parseInt(times/60/60/24)  //得到倒计时天数

    d=d<p>【相关推荐:<a href="https://www.php.cn/course/list/17.html" target="_blank" textvalue="javascript视频教程">javascript视频教程</a>、<a href="https://www.php.cn/course/list/1.html" target="_blank">web前端</a>】</p>

The above is the detailed content of Complete mastery of JavaScript's Date object. 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
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

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 Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools