views:

1137

answers:

4

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?

+1  A: 

You should look into the native JavaScript Date Object methods.

tj111
Is there a way to input the Meridian (am/pm)?
wizard
If you use the Date.parse method, it accepts AM/PM in the string (but requires a full date in front of it).
tj111
it doesn't seem to work with date parse - I keep getting invalid date format
wizard
Try with Date.parse("01/01/2001 12:00 PM"); (There needs to be a space between time time and AM/PM and the date has to be in the format shown)
some
+1  A: 
var time = "";
var hour = Number($("#EventCloseTimeHour option:selected").text())%12 + ($("#EventCloseTimeMeridian option:selected").text() == 'PM'?12:0)) ;


time +=("00"+String(hour)).slice(-2)+":"+ $("#EventCloseTimeMin option:selected").text();

The key to this solution is using the conditional operator "a?b:c" which translates to "if a then b else c"

Michael MacDonald
this breaks with 12:30 pm
wizard
Still breaks with 12:xx AM. You always has to mod the time with 12, and then you add 12 if its PM.
some
+2  A: 

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;
some
I like yours the best so far but I get invalid date out of "toTimeString" and then It slices it up to just say "Invalid ". This is firefox with firebug, but it doesn't work in chrome either. I don't think the date object takes meridians
wizard
Check if you get the right values from the jquerys... If the input is invalid you get an invalid output.
some
A: 

I got it with a few people's answers.

var time = "";
var hour = Number($("#EventCloseTimeHour option:selected").text());
if($("#EventCloseTimeMeridian option:selected").text() == 'PM'){
    hour = String((hour%12) + 12);
}
hour = hour < 10 ? "0" + hour : hour;
time +=hour+":"+ $("#EventCloseTimeMin option:selected").text() + ":00";
wizard
Hours below 10 should be zeropadded. In 24h mode there are always two digits.
some