Table of Contents
Date object instantiation:
1: Instantiation without parameters
2: Instantiation with parameters
3: Formatting year, month and day
五:获取当前时间总毫秒数(时间戳)
六:倒计时案例(重点)
Home Web Front-end JS Tutorial Complete mastery of JavaScript's Date object

Complete mastery of JavaScript's Date object

May 18, 2022 am 11:58 AM
javascript

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

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);  //会输出当前时间
Copy after login

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

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

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());  //输出当前周几
Copy after login

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

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());  //输出当前秒
Copy after login

 

 输出连续格式时分秒:

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

function time()

{

var time=new Date();

var h=time.getHours();

h = h<10 ? '0'+h : h;

var m=time.getMinutes();

m = m<10 ? '0'+m : m;

var s=time.getSeconds();

s = s<10 ? '0'+s : s;

return h+'时'+m+'分'+s+'秒';

}

console.log(time());
Copy after login

五:获取当前时间总毫秒数(时间戳)

这里所说的总毫秒数是指当前时间距离1970年1月1日的总毫秒数,共有四种方法可以表示

valueOf()

getTime()

var date=new Date();

console.log(date.valueOf());   

console.log(date.getTime());
Copy after login

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

var date=+new Date();

console.log(date);
Copy after login

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

console.log(Date.now());
Copy after login

六:倒计时案例(重点)

在日常开发中很多地方都会用的到倒计时,例如淘宝,京东的双十一秒杀倒计时等,我们如何也写出一个倒计时效果呢,我们首先会想到刚才学到的获取当前时间,再减去我们设置好的时间即可,但是我们获取到的标准时间很可能会出现减去之后是负数的情况(例如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<10?'0'+d:d;  //将不足10的时间补0

    var h=parseInt(times/60/60%24)  //得到倒计时小时数

    h=h<10?'0'+h:h;  //将不足10的时间补0

    var m=parseInt(times/60%60)  //得到倒计时分钟数

    m=m<10?'0'+m:m;  //将不足10的时间补0

    var s=parseInt(times%60)  //得到倒计时秒数

    s=s<10?'0'+s:s;  //将不足10的时间补0

    return d + '天' + h + '时' + m + '分' + s +'秒';  //返回倒计时

}

alert('倒计时还剩下' + count('2022-1-18 16:30:00'));  //调用并输入目标的结束时间
Copy after login

【相关推荐:javascript视频教程web前端

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

Video Face Swap

Video Face Swap

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

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

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

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles