Ngày tháng có thể so sánh dễ dàng trong JavaScript. Các ngày có thể thuộc khung thời gian bất kỳ: quá khứ, hiện tại, tương lai. Có thể so sánh ngày quá khứ với tương lai hoặc tương lai với hiện tại.
Ví dụ 1
Trong ví dụ sau, ngày năm 2000 so sánh với hôm nay và thông báo tương ứng hiển thị.
<html> <body>
<p id="compare"></p> <script>
var today = new Date();
var otherday = new Date();
otherday.setFullYear(2000, 2, 14);
if (otherday > today) {
var msg = "The date you provided is a future date ";
} else {
var msg = "The date you provided is a past date";
}
document.getElementById("compare").innerHTML = msg;
</script> </body> </html>
Kết quả
The date you provided is a past date
Ví dụ 2
Trong ví dụ sau, ngày năm 2900 so sánh với hôm nay.
<html> <body>
<p id="compare"> </p> <script>
var today = new Date();
var otherday = new Date();
otherday.setFullYear(2900, 2, 14);
if (otherday > today) {
var msg = "The date you provided is a future date ";
} else {
var msg = "The date you provided is a past date";
}
document.getElementById("compare").innerHTML = msg;
</script> </body> </html>
Kết quả
The date you provided is a future date