如何對比兩個 JavaScript Date 物件?


要使用 JavaScript 比較兩個日期物件,建立兩個日期物件並獲取最新日期來與自定義日期進行比較。

示例

你可以嘗試執行以下程式碼來比較兩個日期 −

線上演示

<!DOCTYPE html>
<html>
   <body>
      <script>
         var date1, date2;
         date1 = new Date();
         document.write(date1);
         date2 = new Date( "Dec 10, 2015 20:15:10" );
         document.write("<br>"+date2);
         if (date1 > date2) {
            document.write("<br>Date1 is the recent date.");
         } else {
            document.write("<br>Date 2 is the recent date.");
         }
      </script>
   </body>
</html>

輸出

Mon May 28 2018 09:48:49 GMT+0530 (India Standard Time)
Thu Dec 10 2015 20:15:10 GMT+0530 (India Standard Time)
Date1 is the recent date

更新時間: 2020 年 6 月 18 日

297 次瀏覽

開始你的職業生涯

完成課程後獲得認證

開始著手
廣告
© . All rights reserved.