JavaScript provides several ways to display date and time in a 12-hour format with AM or PM. Built-in methods such as toLocaleString() and Intl.DateTimeFormat() provide simple formatting options, while native Date methods give more control over the output.
- Use toLocaleString() for a quick and simple 12-hour format.
- Use native Date methods when you need to manually control hours, minutes, and AM/PM.
- Use Intl.DateTimeFormat() for flexible, locale-aware date and time formatting.
Approach 1: Using toLocaleString() Method
The toLocaleString() method returns a localized string representation of a date. By specifying hour and minute options, it can display the time in a 12-hour format with AM or PM.
Example: In this example, toLocaleString() formats the current time into a 12-hour format.
let date = new Date();
let n = date.toLocaleString([], {
hour: "2-digit",
minute: "2-digit"
});
console.log(n);
Approach 2: Using Native Date Methods
In this approach, the getHours() and getMinutes() methods are used to obtain the time. The modulo % operator converts the hour to a 12-hour format, while the conditional operator determines whether the time is AM or PM.
Example: Current time is converted into a 12-hour format using native JavaScript methods.
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
// Check whether AM or PM
let newformat = hours >= 12 ? "PM" : "AM";
// Find current hour in AM-PM format
hours = hours % 12;
// Display "0" as "12"
hours = hours ? hours : 12;
minutes = minutes < 10 ? "0" + minutes : minutes;
console.log(hours + ":" + minutes + " " + newformat);
Approach 3: Using Intl.DateTimeFormat() Constructor
The Intl.DateTimeFormat() constructor provides locale-aware date and time formatting. By setting hour12 to true, the time is displayed using the 12-hour format with AM or PM.
Example: Intl.DateTimeFormat() formats the current time in a 12-hour format.
let date = new Date();
let formatter = new Intl.DateTimeFormat("en-US", {
hour: "2-digit",
minute: "2-digit",
hour12: true,
});
let formattedTime = formatter.format(date);
console.log(formattedTime);