JavaScript Date.getHours() 方法用于根据本地时间检索日期对象的小时值。返回值将是一个介于 0 和 23 之间的整数,表示根据本地时区的小时。
如果 Date 对象创建时不带任何参数,则返回本地时区的当前小时。如果 Date 对象是使用特定日期和时间创建的,则它将返回本地时区中该日期的小时部分。如果 Date 对象无效,则返回 NaN (Not-a-Number)。
语法
以下是 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>
输出
正如我们所看到的,已根据当地时间返回相应的问候语。

