In the previous article "Detailed explanation of how to use JavaScript to print the content of div elements", I introduced how to use JavaScript to print the content of div elements. Interested friends can go and learn about it~
The main content of this article is to teach you how to use JavaScript to compare two dates!
In JavaScript, we can compare two dates by converting them into numerical values corresponding to their times. First, we can convert the Date to a numeric value using the getTime() function; then by converting the given date into a numeric value, we can then compare them directly.
For specific implementation methods, we can look at the following 3 examples:
Code example 1:
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title></title> <script> // 当前日期 var g1 = new Date(); var g2 = new Date(); if (g1.getTime() === g2.getTime()) document.write("两者相等"); else document.write("两者不相等"); javascript: ; </script> </head> <body> </body> </html>
Output:
两者相等
Code example 2:
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title></title> <script> var g1 = new Date(); // (YYYY-MM-DD) var g2 = new Date(2019 - 08 - 03); if (g1.getTime() < g2.getTime()) document.write("g1 小于 g2"); else if (g1.getTime() > g2.getTime()) document.write("g1 大于 g2"); else document.write("两者相等"); javascript: ; </script> </head> <body> </body> </html>
Output:
g1 大于 g2
Code example 3:
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title></title> <script> var g1 = new Date(2019, 08, 03, 11, 45, 55); // (YYYY, MM, DD, Hr, Min, Sec) var g2 = new Date(2019, 08, 03, 10, 22, 42); if (g1.getTime() < g2.getTime()) document.write("g1 小于 g2"); else if (g1.getTime() > g2.getTime()) document.write("g1 大于 g2"); else document.write("两者相等"); javascript: ; </script> </head> <body> </body> </html>
Output:
g1 大于 g2
Note:
getTime()
The function of the getTime()
dateObject.getTime()
→This method is always used in conjunction with a
Date object.
Finally, I would like to recommend "JavaScript Basics Tutorial
" ~ Welcome everyone to learn ~###The above is the detailed content of How to compare two dates using JavaScript. For more information, please follow other related articles on the PHP Chinese website!