Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a simple way to convert between an am/pm time to 24 hour time in javascript

I've been playing with jquery and I've run myself into a time problem. I've got 3 time input select boxes, one for hours, one for minutes, and one for the Meridian. I need to convert this time into a 24 hour string format and then stick it into a hidden input.

var time = "";
time += $("#EventCloseTimeHour option:selected").text();
time += ":" + $("#EventCloseTimeMin option:selected").text() + ":00";
time += " " + $("#EventCloseTimeMeridian option:selected").text();

$("#ConditionValue").val(time);         

This gives me "1:30:00 pm" where I need "13:30:00". Any quick javascript time tips?

like image 348
reconbot Avatar asked Dec 30 '22 05:12

reconbot


1 Answers

Example of tj111 suggestion:

$("#ConditionValue").val(
    (
        new Date(
            "01/01/2000 " + 
            $("#EventCloseTimeHour option:selected").text() +
            $("#EventCloseTimeMin option:selected").text() + ":00" +
            " " +
            $("#EventCloseTimeMeridian option:selected").text()
        )
    ).toTimeString().slice(0,8))
;

Or you can use:

hour = hour %12 + (meridian === "AM"? 0 : 12);
hour = hour < 10 ? "0" + hour : hour;  
like image 115
3 revs Avatar answered Jan 04 '23 23:01

3 revs