0

I see that I various times like

01:45
//and
15:00

I assume that date is HH:MM in military ?

While have I seen some advanced functions then parse sentences and even some using the seconds like HH:MM:SS , I am wanting a simple and accurate way of getting the HH:MM

So I assume 15:00 is 3:00 ?

This function below is not going to work because I already have ":" so below assumed HHMM right? when I believe I need HH:MM to be parsed ?

var getTravelTimeFormatted = function (str) {
    var hours = Math.trunc(str / 60),
        minutes = str % 60;
        return hours + ':' + minutes;
    };

Update

Ok, I assume that 15:00 is 3:00 , right?

So i stripped out the incoming ":" and then add it back problem is the result is 25.0 so what does that mean?

var getTravelTimeFormatted = function (str) {
    str = str.replace(/:/g,'');
    var hours = Math.trunc(str / 60),
    minutes = str % 60;
    return hours + ':' + minutes;
};

console.log(getTravelTimeFormatted('15:00'));

2 Answers2

2

Given a string HH:MM you can just split then subtract 12 hours. Here's a naive solution that doesn't check for invalid input.

function TwelveHourFormat(time) {
    var dtParts = time.split(":");

    var hours = dtParts[0];
    var minutes = dtParts[1];
    var suffix = "AM";

    if (hours > 12) {
        hours = hours - 12;
        suffix = "PM";
    }
    else if (hours == "00") {
        hours = 12;
        suffix = "AM";
    }
    else if (hours == "12") {
        suffix = "PM";
    }

    return (hours + ":" + minutes + " " + suffix);
}
Jasen
  • 14,030
  • 3
  • 51
  • 68
  • I was playing with one I found that was passing in a date... with month day year and time and trying to get rid of the m/d/y was a pain, yours works great thx ! –  Dec 30 '16 at 03:33
0

This is a duplicate of Converting 24 hour time to 12 hour time w/ AM & PM using Javascript. Jasen's answer is fine, and more concise than the duplicate, but the function can be a little more concise:

/* Convert time in 24 hour hh:mm format to 12 hour h:mm ap format
** @param {string} time - in hh:mm format (e.g. 14:30)
** @returns {string} time in 12 hour format (e.g. 2:30 PM)
*/
function to12HourTime(time) {
  var b = time.split(/\D/);
  return (b[0]%12 || 12) + ':' + b[1] +
         (b[0]<11? ' AM' : ' PM');
}

// Some tests
['23:15','2:15','03:15','00:30'].forEach(function(v) {
    console.log(v + ' => ' + to12HourTime(v));
});
Community
  • 1
  • 1
RobG
  • 142,382
  • 31
  • 172
  • 209