Home > Web Front-end > JS Tutorial > js method to determine whether two dates are equal_javascript skills

js method to determine whether two dates are equal_javascript skills

WBOY
Release: 2016-05-16 17:22:56
Original
1462 people have browsed it

For example:

Copy code 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 both objects, and their types are reference types, so if you need to compare them, you need to compare their literal values ​​instead of simply using == to compare.

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

Copy the code 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

Using the getTime() method, you can return the value corresponding to the date, and then compare it.

Actually, there is another way to compare dates.

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

is used here Subtract date2 from date1 to get the time difference between them. If it is 0, it must be equal.
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