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

Tim picture Tim · Dec 16, 2012 · Viewed 129.2k times · Source

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?

Answer

HBP picture HBP · Dec 16, 2012

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.

Working example

(function() {

  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
  }

  var tel = document.getElementById('tests');

  tel.innerHTML = tel.innerHTML.split(/\r*\n|\n\r*|\r/).map(function(v) {
    return v ? v + ' => "' + tConvert(v.trim()) + '"' : v;
  }).join('\n');
})();
<h3>tConvert tests : </h3>
<pre id="tests">
  18:00:00
  18:00
  00:00
  11:59:01
  12:00:00
  13:01:57
  24:00
  sdfsdf
  12:61:54
</pre>