Summary of date-related operations in JavaScript _ basic knowledge-js tutorial

Source: Internet
Author: User
This article mainly introduces the summary of date-related operations in JavaScript, which is the basic knowledge in the JS getting started learning. For more information, see Creation date
The Date object is used to process the Date and time.
You can use the new keyword to define the Date object. The following code defines a Date object named myDate:
There are four ways to initialize the date:

New Date () // current Date and time new Date (milliseconds) // returns the number of milliseconds since January 1, January 1, 1970. new Date (dateString) new Date (year, month, day, hours, minutes, seconds, milliseconds)

Most of the above parameters are optional. If not specified, the default parameter is 0.
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)

Set date
By using the date object method, we can easily operate on the date.
In the following example, we set a specific date for the date object (January 1, January 14, 2010 ):

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

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

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

Note: If the number of days increases, the month or year is changed, and the date object is automatically converted.
Comparison of Two dates
A date object 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("Today is before 14th January 2100"); }else { alert("Today is after 14th January 2100"); }

How to Use the Date () method to obtain the Date of the current day.
Source code:

​《script》​var d=new Date();document.write(d);​《script》​  

Test results:

Sat Oct 24 2015 15:14:48 GMT + 0800 (Chinese Standard Time)
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.