Date.prototype.setHours
Sets the hours for a specified date according to local time
Syntax
date.setHours(hoursValue, minutesValue?, secondsValue?, msValue?)Parameters
| Parameter | Type | Description |
|---|---|---|
| hoursValue | number | An integer from 0 to 23 |
| minutesValue | number | Optional minutes (0-59) |
| secondsValue | number | Optional seconds (0-59) |
| msValue | number | Optional milliseconds (0-999) |
Return Value
The number of milliseconds from epoch for the updated date
Examples
const date = new Date();
date.setHours(0, 0, 0, 0);
console.log(date.getHours()); // 0 (midnight)function startOfDay(date: Date) {
const d = new Date(date);
d.setHours(0, 0, 0, 0);
return d;
}function endOfDay(date: Date) {
const d = new Date(date);
d.setHours(23, 59, 59, 999);
return d;
}Understanding Date.prototype.setHours
The Date.prototype.setHours method in JavaScript sets the hours for a specified date according to local time. It belongs to the Date object and is one of the most widely used methods for working with date values in modern JavaScript and TypeScript applications.
The method signature is date.setHours(hoursValue, minutesValue?, secondsValue?, msValue?). It accepts 4 parameters: hoursValue, minutesValue, secondsValue. When called, it returns the number of milliseconds from epoch for the updated date. Understanding when and how to use setHours() helps you write more expressive, readable code.
Common use cases for Date.prototype.setHours include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like date-gethours, date-setdate, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Date.prototype.setHours is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
More Date Methods
Other methods in the Date object
Related Tools
More Date Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.