Skip to content
Advertisements

JavaScript Date.setHours()

Why setHours ?

The JavaScript Date setHours () method is a built-in function. Sets the time of a specific date according to local time. This method can also be used to set minutes, seconds, and milliseconds.

Syntax:

Date.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])

  • hoursValue: An integer from 0 to 23 representing the time.
  • minutesValue: An integer from 0 to 59 representing the minutes.
  • secondsValue: An integer from 0 to 59 represents the second.
  • msValue: Between 0 and 999, a number representing milliseconds. If you specify the MsValue parameter, you must also specify minutesValue and secondsValue.

Return:

  • It returns the new date with updated hour which is set by setHours() function.

JavaScript setHours Examples

Example 1

The Date setHours () method can change the time of today’s date.

        var date = new Date();
        console.log(date.getHours());

        date.setHours(22);
        console.log(date.getHours());

8
22


Example 2

The Date setHours () method can change the time of a specific date.

        var date = new Date('April 21, 1983 22:47:55');
        console.log(date.getHours());

        date.setHours(10);
        console.log(date.getHours());

22
10


Example 3

        var date = new Date('April 21, 1983 22:47:55');
        date.setHours(12, 20, 55);

        let hour = date.getHours()
        console.log(hour);

        let minute = date.getMinutes()
        console.log(minute);

        let second = date.getSeconds()
        console.log(second);

12
20
55


Example 4

In the setHours () method, if you enter the time more than 24, it will move to the next day. Enter the value of 33 for the period. 33 – 24 = 9. Goes to the next day. And it’s 9:00.

        var date = new Date('April 21, 1983 22:47:55');
        date.setHours(33);

        console.log(date.getDay())

5


Browser Support

Chromeyes
Edgeyes
Firefox1
Internet Exploreryes
Operayes
Safariyes
Android webviewyes
Chrome for Androidyes
Edge mobileyes
Firefox for Android4
Opera Androidyes
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: