Sometimes, we want to convert 24 hour time to 12 hour time with AM & PM using JavaScript.
In this article, we’ll look at how to convert 24 hour time to 12 hour time with AM & PM using JavaScript.
How to convert 24 hour time to 12 hour time with AM & PM using JavaScript?
To convert 24 hour time to 12 hour time with AM & PM using JavaScript, we use the toLocaleString method.
For instance, we write
const date = new Date("February 04, 2022 19:00:00");
const options = {
hour: "numeric",
minute: "numeric",
hour12: true,
};
const timeString = date.toLocaleString("en-US", options);
console.log(timeString);
to call toLocaleString with the locale string and the options object.
In options, we set hour12 to true to return a string with 12 hour time and AM or PM.
hour and minute are set to numeric to return them as numbers.
Conclusion
To convert 24 hour time to 12 hour time with AM & PM using JavaScript, we use the toLocaleString method.