JavaScript: Get 24-hour format of an hour without leading zeros
JavaScript Datetime: Exercise-34 with Solution
24-Hour Format
Write a JavaScript function to get the 24-hour format of an hour without leading zeros.
Test Data :
dt = new Date(1989, 10, 1);
console.log(hours_without_zeroes(dt));
0
Sample Solution:
JavaScript Code:
// Define a function named 'hours_without_zeroes' that takes a Date object 'dt' as input
function hours_without_zeroes(dt)
{
// Return the hour component of the given date, without leading zeroes
return dt.getHours();
}
// Create a new Date object representing the current date and time
dt = new Date();
// Print the hour component of the current date, without leading zeroes
console.log(hours_without_zeroes(dt));
// Create a new Date object representing a specific date (November 1, 1989)
dt = new Date(1989, 10, 1);
// Print the hour component of the specific date, without leading zeroes
console.log(hours_without_zeroes(dt));
Output:
15 0
Explanation:
The above JavaScript code defines a function named "hours_without_zeroes()" that takes a "Date" object as input and returns the hour component of the date without leading zeroes. It then creates two "Date" objects - one representing the current date and time, and another representing November 1, 1989. It prints the hour component of each date object using the "hours_without_zeroes()" function, demonstrating how it works.
Flowchart:
Live Demo:
See the Pen JavaScript - Get 24-hour format of an hour without leading zeros-date-ex-34 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to get 12-hour format of an hour with leading zeros.
Next: Write a JavaScript function to get minutes with leading zeros (00 to 59).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics