Home > Web Front-end > JS Tutorial > Summary of date-related operations in JavaScript_Basic knowledge

Summary of date-related operations in JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 15:35:23
Original
1213 people have browsed it

Creation date
Date object is used to handle date and time.
Date objects can be defined using 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 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 example below, 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 example below, we set the date object to a date 5 days from now:

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 to January 14, 2100:

var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();

if (x>today)
 {
 alert("Today is before 14th January 2100");
 }
else
 {
 alert("Today is after 14th January 2100");
 }

Copy after login

How to use the Date() method to get today’s date.
Source code:

<!DOCTYPE html>
<html>
<body>
&#8203;
<script>
&#8203;
var d=new Date();
document.write(d);
&#8203;
</script>
&#8203;
</body>
</html>  
Copy after login

Test results:

Sat Oct 24 2015 15:14:48 GMT+0800 (中国标准时间)
Copy after login

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