Home » JavaScript

Date setHours() method with example in JavaScript

JavaScript Date setHours() method: Here, we are going to learn about the setHours() method in JavaScript with example.
Submitted by IncludeHelp, on March 13, 2019

JavaScript Date setHours() method

setHours() method is a Date class method, it is used to set the hour to the Date object with a valid hour value (between 00 to 23).

Note: Hour value larger than the 23 will be truncated from the starting hour value (0), for example, we are going to set 26 as an hour value, it will be truncated as 2.

Syntax:

    var dt = new Date();
    dt.setHours(hour);

Examples:

    Input/Date class object declaration:
    var dt = new Date();

    Function call to set the hour:
    dt.setHours(16);

    Function call to get the hour:
    dt.getHours(); 
    
    Output:
    16

JavaScript code to demonstrate an example of Date.setHours() method

<html>
<head><title>JavaScipt Example</title></head>

<body>
<script>
	var dt = new Date();
	//getting current hour
	var hour = dt.getHours();
	//printing
	document.write("hour: " + hour + "<br>");
	
	//setting hour to 16
	dt.setHours(16);
	//getting & printing hour again
	hour = dt.getHours();
	document.write("hour: " + hour + "<br>");	

	//setting invalid hour
	//setting hour to 26
	dt.setHours(26);
	//getting & printing hour again
	hour = dt.getHours();
	document.write("hour: " + hour + "<br>");		
</script>
</body>
</html>

Output

hour: 19
hour: 16
hour: 2

Reference: JavaScript setHours() Method






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.