How to Get Time in 12 Hour AM/PM Format in Javascript

To get time in 12-hour AM/PM format in JavaScript, use the toLocaleString() method. The toLocaleString() method returns a string with a language-sensitive date representation.

Syntax

toLocaleString(locales,options);

Parameters

It takes two parameters: locales and options. But these are also optional.

  1. Locales –  We can specify that en-us, etc.
  2. Options –  We specify format etc.

Example

const d = new Date();
const result = d.toLocaleString("en-US", {
 hour: "numeric",
 minute: "numeric",
 hour12: true,
});
console.log("Result : ", result);

Output

Result : 11:20 AM

Get 12-hour AM/PM format using toLocaleTimeString()

The toLocaleTimeString() method returns a string with a language-sensitive representation of the time portion of the date. It is precisely like the toLocaleString() function but has a few differences.

Here is a code example:

const d = new Date();
const result = d.toLocaleTimeString("en-US", {
 hour: "numeric",
 minute: "numeric",
 hour12: true,
});
console.log("Result : ", result);

Output

Result : 11:52 AM

The above example displays a 12-hour time format using the toLocaleTimeString() function. Then, we pass our options and, based on that, will give a time representation string.

Get time 12-hour AM/PM format using a custom function

We can format our time in 12 hours using our custom function logic.

const timeFormat12Hour = (date) => {
   let h = date.getHours();
   let m = date.getMinutes();
   let ampm = h >= 12 ? "pm" : "am";

   h = h % 12; //reminder
   h = h ? h : 12;

   m = m.toString().padStart(2, "0");
  const formatedTimeString = h + ":" + m + " " + ampm;
  return formatedTimeString;
};
console.log("Result : ", timeFormat12Hour(new Date()));

Output

Result : 11:57 am

In the above example, we build our custom function to get and print the 12-hour time format. We can change our logic based on our requirements in this custom function.

Using moment.js library

Using the moment library to get the 12-hour format, use the moment().format() function in JavaScript. The Moment.js format and manipulate time/date in different formats. It is a modern time/date Javascript library.

To work with the moment module in JavaScript, install it using the node package manager.

npm install moment

To use it in your current file, import the moment module using the import statement.

Here is the code example:

import moment from "moment"

const time = moment(new Date()).format("hh:mm a");
console.log("Result : ", time);

Output

Result : 12:03 pm

In the above example, we use the moment.js library to display the 12-hour format if we work on a big project where we need to manipulate or format date or time, so moment js is the best library.

Related posts

How to Convert Timestamp to Date

How to Convert Date to Timestamp

How to Convert String to Date

How to Generate Dates Between Two Dates