Dev HelpersOpen library
← Back

Time Conversion · code 01

Preserved from the original JavaScript Field Guide. Some entries are React fragments that require the surrounding component.

Open this example in the interactive library

Source code

function timeConversion(s: string): string {
     const isPM = s.includes("PM");
  const timeParts = s.slice(0, -2).split(":");
  let hours = parseInt(timeParts[0], 10);

  if (isPM && hours < 12) {
    hours += 12;
  } else if (!isPM && hours === 12) {
    hours = 0;
  }

  const hoursString = hours.toString().padStart(2, "0");
		const formattedTime = `${hoursString}:${timeParts[1]}:${timeParts[2]}`

  return formattedTime;

}