如何在 JavaScript 中比較日期?
在 JavaScript 中,日期比較很容易,日期可以屬於任何時間範圍,例如過去、現在或未來。過去日期可以與未來日期比較,未來日期可以與過去和現在日期比較。
Date 物件可以滿足你的需求,為每個日期建立一個 Date 物件,然後使用 (>,<,<= 或 >=) 進行比較。==, !=, === 和 !== 運算子需要使用date.getTime()。
在 JavaScript 中,我們可以透過將日期轉換為與其時間相對應的數值來比較兩個日期。首先,我們可以使用getTime()方法將日期轉換為數值,然後直接比較這些數值。
示例 1
在下面的示例中,我們將當前日期與提供的日期進行比較。
<!DOCTYPE html>
<html>
<head>
<title>Compare the date with other date</title>
</head>
<body>
<p id="compare"></p>
<script>
var today = new Date();
var otherday = new Date();
otherday.setFullYear(2022, 01, 19);
if (otherday > today) {
var date = "The date you provide is a future date";
} else {
var date = "The date you provide is a past date";
}
document.getElementById("compare").innerHTML = date;
</script>
</body>
</html>
示例 2
下面的示例說明了使用getTime()函式比較日期。
<!DOCTYPE html>
<html>
<head>
<title>Compare the date with other date</title>
</head>
<body>
<p id="compare"></p>
<script>
var d1 = new Date();
var d2 = new Date();
if (d1.getTime() === d2.getTime()) document.write("Both are equal");
else document.write("Not equal");
</script>
</body>
</html>
示例 3
在下面的示例中,JavaScript 程式碼說明了如何比較兩個給定的日期。
<!DOCTYPE html>
<html>
<head> </head>
<body>
<script>
var d1 = new Date(2019, 08, 03, 11, 45, 55); // (YYYY, MM, DD, Hr, Min, Sec)
var d2 = new Date(2019, 08, 03, 11, 45, 55);
if (d1.getTime() < d2.getTime())
document.write("d1 is lesser than d2");
else if (d1.getTime() > d2.getTime())
document.write("d1 is greater than d2");
else document.write("both are equal");
</script>
</body>
</html>
示例 4
在下面的示例中,我們比較了兩個日期,但邏輯是 day1 自動獲取當前日期,day2 傳入日期。
注意 - 如果傳入月份值,則月份值為月份值 - 1,例如 - 如果你想傳入一月,則值為 1-1 = 0,二月值為 1,以此類推。可以直接說它像陣列索引一樣取值,0,1,2,3,4……
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>date compare</title>
</head>
<body>
<script>
var day1 = new Date();
day1.setHours(0, 0, 0, 0);
var day2 = new Date(2022, 06, 20);
day2.setHours(0, 0, 0, 0); //here we are stoping the clock
document.write("day1=>", day1);
document.write("<br \>day2=>", day2);
if (day1 > day2) {
document.write("<br \>day1 is greater than day2");
} else if (day1 < day2) {
document.write("<br \>day1 is older than day2");
} else {
document.write("<br \>day1 and day2 are same");
}
</script>
</body>
</html>
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP