Home > Web Front-end > JS Tutorial > body text

JavaScript Date (date) related knowledge and usage

jacklove
Release: 2018-05-07 10:14:50
Original
1579 people have browsed it

JavaScript Date (date) is widely used in web pages. This article explains it in detail.

Creation Date

Date object is used to handle date and time.

Date objects can be defined through the new keyword. The following code defines a Date object named myDate:

There are four ways to initialize the date:

new Date() // 当前日期和时间
new Date(milliseconds) //返回从 1970 年 1 月 1 日至今的毫秒数
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Copy after login

Most of the above parameters are optional. If not specified, the default The parameter is 0.

Some examples of instantiating a date:

var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)
Copy after login

Set Date

We can easily operate on dates by using methods on date objects.

In the following example, we set a specific date (January 14, 2010) for the date object:

var myDate=new Date();
myDate.setFullYear(2010,0,14);
Copy after login

In the following example, we set the date object to Date 5 days later:

var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
Copy after login

Note: If adding days would change the month or year, the date object will automatically complete this conversion.

Comparison of two dates

Date objects can also be used to compare two dates.

The following code compares the current date with January 14, 2100:

var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();if (x>today){    
alert("今天是2100年1月14日之前");}
else{   
 alert("今天是2100年1月14日之后");
 }
Copy after login

This article introduces in detail the specific usage of Date in js and related precautions, more For relevant knowledge, please pay attention to the php Chinese website.

Related recommendations:

Introduction to the use of JavaScript RegExp objects

Several common JS sorting codes on the front end

About how to use JavaScript Array (array) object

The above is the detailed content of JavaScript Date (date) related knowledge and usage. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!