Convert Military Time To Standard Time With JavaScript

I was recently tasked with creating a function to convert the provided military time to standard AM/PM time. I searched around a bit and couldn’t find much on it so I thought I would share what I came up with. Comments and suggestions are welcome.

Example Call To Function

var myMilTime = '14:30:36';
var myStandardTime = milToStandardTime ( myMilTime );

Function

function milToStandard(value) {
  if (value !== null && value !== undefined){ //If value is passed in
    if(value.indexOf('AM') > -1 || value.indexOf('PM') > -1){ //If time is already in standard time then don't format.
      return value;
    }
    else {
      if(value.length == 8){ //If value is the expected length for military time then process to standard time.
        var hour = value.substring ( 0,2 ); //Extract hour
        var minutes = value.substring ( 3,5 ); //Extract minutes
        var identifier = 'AM'; //Initialize AM PM identifier

        if(hour == 12){ //If hour is 12 then should set AM PM identifier to PM
          identifier = 'PM';
        }
        if(hour == 0){ //If hour is 0 then set to 12 for standard time 12 AM
          hour=12;
        }
        if(hour > 12){ //If hour is greater than 12 then convert to standard 12 hour format and set the AM PM identifier to PM
          hour = hour - 12;
          identifier='PM';
        }
        return hour + ':' + minutes + ' ' + identifier; //Return the constructed standard time
      }
      else { //If value is not the expected length than just return the value as is
        return value;
      }
    }
  }
};

Example Return

2:30 PM

Leave a comment

Your email address will not be published. Required fields are marked *


7 × eight =