convert 24 hours to 12 hours javascript

function convertTo12HourFormat(hours) {
  if (hours === 0) {
    return 12;
  } else if (hours > 12) {
    return hours - 12;
  } else {
    return hours;
  }
}

function getAMPM(hours) {
  return hours >= 12 ? 'PM' : 'AM';
}

function convertTo12HourTime(time) {
  const hours = parseInt(time.substr(0, 2));
  const minutes = time.substr(3, 2);
  const period = getAMPM(hours);
  const twelveHourFormat = convertTo12HourFormat(hours);
  return `${twelveHourFormat}:${minutes} ${period}`;
}

const twentyFourHourTime = '15:30';
const twelveHourTime = convertTo12HourTime(twentyFourHourTime);
console.log(twelveHourTime); // Output: 3:30 PM

Code Explanation

  • The convertTo12HourFormat function takes the 24-hour format hours and converts them to 12-hour format.
  • The getAMPM function determines whether the time is AM or PM based on the input hours.
  • The convertTo12HourTime function parses the input time, converts the hours to 12-hour format, and returns the time in the format "hh:mm AM/PM".
  • Lastly, an example is shown, converting the 24-hour time '15:30' to 12-hour time, which results in '3:30 PM'. ```