JavaScript getHours 函数是 Date 函数之一,用于返回给定日期的小时数。在这里,我们使用 getHours 函数从当前日期和时间返回小时数。
<!DOCTYPE html>
<html>
<head>
<title> JS </title>
</head>
<body>
<h1> Example </h1>
<script>
var dt = Date();
document.write("Date and Time : " + dt);
document.write("Hours : " + dt.getHours());
</script>
</body>
</html>
Example
Date and Time: Sat Nov 03 2018 18:11:34 GMT+0530 (Indian Standard Time)
Hours : 18
在此 get Hours 函数示例中,我们从自定义日期中提取小时。
<!DOCTYPE html>
<html>
<head>
<title> JavaScriptGetHoursFunction </title>
</head>
<body>
<h1> JavaScriptgetHoursFunctionExample </h1>
<script>
var dt = Date("April 29, 2012 12:09:07");
document.write("Date and Time : " + dt);
document.write("Hours using getHours(): " + dt.getHours());
</script>
</body>
</html>

此 JavaScript get hours 示例从不包含小时的自定义日期中提取小时,并返回 0 小时。
<!DOCTYPE html>
<html>
<head>
<title> JS </title>
</head>
<body>
<h1> Example </h1>
<script>
var dt = Date("April 29, 2012");
document.write("DateTime : " + dt);
document.write("Hours : " + dt.getHours());
</script>
</body>
</html>
Example
DateTime: Sun Apr 29 2012 00:00:00 GMT+0530 (Indian Standard Time)
Hours : 0