Tim Tim - 14 days ago 8
Javascript Question

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

The server is sending a string in this format:

18:00:00
. This is a time-of-day value independent of any date. How to convert it to
6:00PM
in Javascript? I could prepend today's date as a string to the value sent by the server and then parse the combined values and then try the
.toTimeString()
method of the Date object, but the format that time method emits is 24-hour time with a seconds chunk. I could write a function, but is there something built in?

HBP HBP
Answer

Nothing built in, my solution would be as follows :

function tConvert (time) {
  // Check correct time format and split into components
  time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

  if (time.length > 1) { // If time format correct
    time = time.slice (1);  // Remove full string match value
    time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
    time[0] = +time[0] % 12 || 12; // Adjust hours
  }
  return time.join (''); // return adjusted time or original string
}

tConvert ('18:00:00');

This function uses a regular expression to validate the time string and to split it into its component parts. Note also that the seconds in the time may optionally be omitted. If a valid time was presented, it is adjusted by adding the AM/PM indication and adjusting the hours.

The return value is the adjusted time if a valid time was presented or the original string.

See jsFiddle : http://jsfiddle.net/ZDveb/