How to Get Hours and Minutes From Date in JavaScript

So, you are probably here because you are struggling to fetch hours and minutes from a date in JavaScript. There are built-in methods by which you can get hours and minutes from a date in JavaScript, and all those methods are discussed in this post. Let’s have a look.

Get Hours and Minutes From Date in JavaScript

You can use getHours() and getMinutes() methods to get the hours and minutes from a date in Javascript. We simply call two functions, getHours and getMinutes, on a date instance.

The getHours() method returns the hour for the specified date(according to local time.). 

The getMinutes() method returns the minutes for the specified date(according to local time.). 

Syntax

getHours() ;

getMinutes();

Return value

A string representing the time.

Example 

const now = new Date();

const current = now.getHours() + ':' + now.getMinutes();

console.log(current);

Output

11:10

Explanation

  • First, create a variable named now you can create a variable with any name but here I’ am, using now because we are talking about the current time. Then we assign a new instance of date to it. Our variable now has the date in it.
  • Then we are creating another variable and, in that variable, we are refreshing hours and minutes from our upper variable using the getHours and getMinutes methods.
  • At last, when we print our variable to the console, it comes up with the hours and minutes.

How to display hours and minutes in 12 Hours Format(AM/PM Format)

If you want your time to be displayed in a 12-hours format(am/pm format), then we have a solution for you. Check out the syntax, explanation, and output of the below code.

Syntax

<time>.toLocalTimeString(<language-region>,formats);

Return Value

A string with a language-sensitive representation of the time portion of the date

Example 

const now = new Date();

const ampm = now.toLocaleTimeString('default', {

    hour: '2-digit',

    minute: '2-digit'

  });  

console.log(ampm);

Output

11:16 AM

Explanation

  • First of all, create a variable and store a new instance of the date in it.
  • Then on that variable, I am calling  toLocaleTimeString() method to get a locale-specific representation of the hours and minutes and pass 2 arguments to it.
  • The first argument is the default for the locale and got the hours and minutes formatted as HH:MM AM/PM. You can also pass ‘en-US’ for the same. The second argument is an options object where we can set both properties to ‘2 digit’.
  • Then finally, we store it in a variable and print it to the console.

Conclusion

In this article, we have learned how to get hours and minutes from a date in JavaScript. These concepts are usually used when you are working with pre-planned events, delayed events, or scheduled events. I hope that this post was helpful for you and that you found this content informative.

Leave a Comment