How To Convert 24 Hours To 12 Hours In JavaScript

Hello devs, In this javascript tutorial, I am going to show you how to convert 24 hour time to 12 hour time in javascript. We will create a custom javascript method to convert 24 hour time to 12-hour human-readable format in javascript.

You can use moment js to covert time. But i will use my own code to convert 24 hour time into 12 hour time with am pm.  So hope this tutorial will help you to convert javascript time into a 12-hour format.

If you don't know how to convert it, then this example is for you. So let's see the source code of gethours in 12 hour format:

 const convert24hourTo12HourFormat = (time) => {
    const time_part_array = time.split(":");
    let ampm = 'AM';
    if (time_part_array[0] >= 12) {
        ampm = 'PM';
    }
    if (time_part_array[0] > 12) {
        time_part_array[0] = time_part_array[0] - 12;
    }
    const formatted_time = time_part_array[0] + ':' + time_part_array[1] + ':' + time_part_array[2] + ' ' + ampm;
    return formatted_time;
  }

 

Read also: Handling Object Properties using Optional Chaining in JavaScript

 

Hope this example will help you.

 

#javascript