JavaScript Date getHours() 方法



JavaScript 的 Date.getHours() 方法用於根據本地時間檢索日期物件的時值。返回值將是介於 0 和 23 之間的整數,表示根據本地時區的時。

如果 Date 物件在沒有引數的情況下建立,則返回本地時區的當前時。如果 Date 物件使用特定的日期和時間建立,則返回該日期在本地時區中的時分量。如果 Date 物件無效,則返回 NaN(非數字)。

語法

以下是 JavaScript Date getHours() 方法的語法:

getHours();

此方法不接受任何引數。

返回值

此方法返回一個整數,表示給定日期物件的時分量,範圍從 0 到 23。

示例 1

在下面的示例中,我們演示了 JavaScript Date getHours() 方法的基本用法:

<html>
<body>
<script>
   const currentDate = new Date();
   const currentHour = currentDate.getHours();

   document.write("Current Hour:", currentHour);
</script>
</body>
</html>

輸出

以上程式根據本地時間返回當前時。

示例 2

在此示例中,我們從特定的日期和時間檢索時。

<html>
<body>
<script>
   const customDate = new Date('2023-01-25T15:30:00');
   const Hour = customDate.getHours();

   document.write("Hour:", Hour);
</script>
</body>
</html>

輸出

以上程式返回整數 15 作為時。

示例 3

根據當前本地時間,程式將根據是上午、下午還是晚上返回問候語。

<html>
<body>
<script>
   function getTimeOfDay() {
      const currentHour = new Date().getHours();

      if (currentHour >= 6 && currentHour < 12) {
         return "Good morning...";
      } else if (currentHour >= 12 && currentHour < 18) {
         return "Good afternoon...";
      } else {
         return "Good evening...";
      }
   }

   const greeting = getTimeOfDay();

   document.write(greeting);
</script>
</body>
</html>

輸出

如我們所見,根據本地時間返回了相應的問候語。

廣告