ilija veselica
ilija veselica

Reputation: 9574

Convert timestamp from am/pm to 24-hour in Javascript

I'm using jquery timepicker. On user side, time needs to be displayed as am/pm format (10:30am or 5:30pm). I need to append that value to datepicker value. For example, if datepicker value is 07/08/2015, final value should be 07/08/2015 17:30. Problem here is in converting 5:30pm to 17:30. How to do it with javascript

Upvotes: 0

Views: 1928

Answers (2)

Rajeev Singh
Rajeev Singh

Reputation: 11

In case you want to convert from the 12 Hour system(hh:mm:ssPM/AM) to 24 Hour system then you could use the following

function timeConversion(s) {
    const timeString = s.toString()
    if (timeString.match(/PM$/)) {
        var match = timeString.match(/([0-9]+):([0-9]+):([0-9]+)PM/)
        var hours = parseInt(match[1]) + 12;
        var minutes = match[2];
        var second = match[3]; parseInt(match[1])
        if (parseInt(match[1]) === 12) {
            return parseInt(match[1])+ ':' + minutes + ':' + second;
        } else {
            return hours + ':' + minutes + ':' + second;
        }
    } else {
        var match = timeString.match(/([0-9]+):([0-9]+):([0-9]+)AM/)
        var hours = parseInt(match[1]);
        var minutes = match[2];
        var second = match[3];
        if (hours === 12) {
            return '00:' + minutes + ':' + second;
        } else {
            return timeString.replace('AM', '');
        }
    }
}

Upvotes: 0

bvaughn
bvaughn

Reputation: 13487

You could write your own conversion function that converts time-strings with "pm" in them by adding 12 hours, like so:

var convertTimeStringTo24Hours = function(timeString) {
  if (timeString.match(/pm$/)) {
    var match = timeString.match(/([0-9]+):([0-9]+)pm/);
    var hours = parseInt(match[1]) + 12;
    var minutes = match[2];
    return hours + ':' + minutes;
  } else {
    return timeString.replace('am', '');
  }
};

Upvotes: 2

Related Questions