How to Extract the Hour from a String in JavaScript?

Estimated read time 1 min read

You can extract the hour from a string that represents a date in JavaScript by creating a Date object and using its getHours method.

Here’s an example:

let dateStr = "2022-12-31T12:30:00";
let date = new Date(dateStr);
let hour = date.getHours();
console.log(hour);
// Output: 12

In the example, a Date object is created from the string "2022-12-31T12:30:00" using the Date constructor. The getHours method is then used to extract the hour from the Date object, which is 12 in this case.

Note that the string must be in a format that can be recognized by the Date constructor, such as the ISO-8601 format used in the example. If the string is not in a recognizable format, you may need to use regular expressions or other string manipulation techniques to extract the hour from the string and create a Date object from it.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply