convert 12-hour hh:mm AM/PM to 24-hour hh:mm

Try this

var time = $("#starttime").val();
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" + sHours;
if(minutes<10) sMinutes = "0" + sMinutes;
alert(sHours + ":" + sMinutes);

This question needs a newer answer :)

const convertTime12to24 = (time12h) => {
  const [time, modifier] = time12h.split(' ');

  let [hours, minutes] = time.split(':');

  if (hours === '12') {
    hours = '00';
  }

  if (modifier === 'PM') {
    hours = parseInt(hours, 10) + 12;
  }

  return `${hours}:${minutes}`;
}

console.log(convertTime12to24('01:02 PM'));
console.log(convertTime12to24('05:06 PM'));
console.log(convertTime12to24('12:00 PM'));
console.log(convertTime12to24('12:00 AM'));


I had to do something similar but I was generating a Date object so I ended up making a function like this:

function convertTo24Hour(time) {
    var hours = parseInt(time.substr(0, 2));
    if(time.indexOf('am') != -1 && hours == 12) {
        time = time.replace('12', '0');
    }
    if(time.indexOf('pm')  != -1 && hours < 12) {
        time = time.replace(hours, (hours + 12));
    }
    return time.replace(/(am|pm)/, '');
}

I think this reads a little easier. You feed a string in the format h:mm am/pm.

    var time = convertTo24Hour($("#starttime").val().toLowerCase());
    var date = new Date($("#startday").val() + ' ' + time);

Examples:

        $("#startday").val('7/10/2013');

        $("#starttime").val('12:00am');
        new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
        Wed Jul 10 2013 00:00:00 GMT-0700 (PDT)

        $("#starttime").val('12:00pm');
        new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
        Wed Jul 10 2013 12:00:00 GMT-0700 (PDT)

        $("#starttime").val('1:00am');
        new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
        Wed Jul 10 2013 01:00:00 GMT-0700 (PDT)

        $("#starttime").val('12:12am');
        new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
        Wed Jul 10 2013 00:12:00 GMT-0700 (PDT)

        $("#starttime").val('3:12am');
        new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
        Wed Jul 10 2013 03:12:00 GMT-0700 (PDT)

        $("#starttime").val('9:12pm');
        new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
        Wed Jul 10 2013 21:12:00 GMT-0700 (PDT)