How to display JavaScript Datetime in 12 hour AM/PM


To display a JavaScript Date object in a 12-hour format with AM/PM, you can use the toLocaleString() method with the hour12 and hour options set.

Here’s an example:

const date = new Date();
const formattedDate = date.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
console.log(formattedDate); // e.g. "11:30 AM" or "5:45 PM"

In this example, we’re creating a new Date object with the current date and time. We’re then using the toLocaleString() method to format the date as a string in the user’s locale.

The 'en-US' argument specifies the locale as US English. The { hour: 'numeric', minute: 'numeric', hour12: true } argument specifies the options for the formatting.

The hour: 'numeric' option formats the hour component as a number, using a 12-hour clock when hour12 is true.

The minute: 'numeric' option formats the minute component as a number.

The hour12: true option specifies that the time should be displayed in a 12-hour format with AM/PM.

Finally, we’re assigning the formatted date string to the formattedDate variable and logging it to the console.