How to Get AM or PM from a Date with JavaScript?

Sometimes, we want to get AM or PM from a date with JavaScript.

In this article, we’ll look at how to get AM or PM from a date with JavaScript.

Get AM or PM from a Date with JavaScript

To get AM or PM from a date with JavaScript, we can use the toLocaleTimeString method.

For instance, we write:

const now = new Date()
  .toLocaleTimeString([], {
    hour: '2-digit',
    minute: '2-digit',
    hour12: true
  })
  .toLowerCase();
console.log(now)

to call toLocateTimeString on a date.

The 2nd argument is an object with the hour and minute set to the hour and minute format of our choice.

hour12 is set to true so that we see am and pm returned.

Therefore, now should be a time like '11:16 am'.

Conclusion

To get AM or PM from a date with JavaScript, we can use the toLocaleTimeString method.