Javascript method for determining whether two dates are equal _ javascript skills

Source: Internet
Author: User
Tags date1
You must have encountered such a situation that there are two date objects, and then you need to determine whether they are equal. The following method is used to determine:

The Code is as follows:


Var date1 = new Date ("2013-11-29 ");
Var date2 = new Date ("2013-11-29 ");
Console. log (date1 = date2); // false


Here, date1 and date2 look the same, but running date1 = date2 returns false. This is because date1 and date2 are all objects and their types are reference types. Therefore, if you need to compare them, you need to compare their literal values rather than simply using =.

If you want to compare whether two dates are equal, you can write

The Code is as follows:


Var date1 = new Date ("2013-11-29 ");
Var date2 = new Date ("2013-11-29 ");
Console. log (date1.getTime () = date2.getTime (); // true


You can use the getTime () method to return the value corresponding to the date and then compare it.

In fact, there is another way to compare dates.

The Code is as follows:


Var date1 = new Date ("2013-11-29 ");
Var date2 = new Date ("2013-11-29 ");
Console. log (date1-date2 = 0); // true


Here, we use date1 minus date2 to obtain the time difference between them. If it is 0, it must be equal.
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.