How to Get Time in 12 Hour Format in JavaScript?

How to Get Time in 12 Hour Format in JavaScript?

This tutorial shows, how to get time in 12 hour format in JavaScript. Below are the examples of custom JavaScript functions that return the time in 12 hours (AM/PM) format. The first JS function returns the time in AM/PM format of a given date and the second JS function returns the current time in 12-hour format.

1

Get Time in 12-Hour Format in JavaScript Example

The following JavaScript function takes a date argument and returns the time in 12-hour (AM/PM) format.

function get12HourTime(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var sTime = hours + ':' + minutes + ' ' + ampm;
  return sTime;
}

console.log(get12HourTime(new Date));
2

Get Current Time in 12-Hour Format in JS

The following JavaScript code, prints the current time on console in 12-hour format.

const date = new Date()
const options = {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
};
const time = new Intl.DateTimeFormat('en-US', options).format(date)
console.log(time)