Categories
JavaScript Answers

How to convert 24-hour time-of-day string to 12-hour time with AM/PM and no time zone with JavaScript?

Spread the love

Sometimes, we want to convert 24-hour time-of-day string to 12-hour time with AM/PM and no time zone with JavaScript.

In this article, we’ll look at how to convert 24-hour time-of-day string to 12-hour time with AM/PM and no time zone with JavaScript.

How to convert 24-hour time-of-day string to 12-hour time with AM/PM and no time zone with JavaScript?

To convert 24-hour time-of-day string to 12-hour time with AM/PM and no time zone with JavaScript, we use the toLoclaeTimeString method.

For instance, we write

const timeString = "18:00:00";

const timeString12hr = new Date(
  "1970-01-01T" + timeString + "Z"
).toLocaleTimeString("en-US", {
  timeZone: "UTC",
  hour12: true,
  hour: "numeric",
  minute: "numeric",
});

to create a date from timeString.

Then we call toLocaleTimeString with the locale and an object with the options.

We set hour12 to true to make it return a 12 hour time string.

Conclusion

To convert 24-hour time-of-day string to 12-hour time with AM/PM and no time zone with JavaScript, we use the toLoclaeTimeString method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *