Abudayah
Abudayah

Reputation: 3875

jquery convert time format

i have text input to enter time and some times I need to change time from 12 hr format to 24 format when I double click on input.. so how can me convert time like this:

1:00 => 13:00

01:00 => 13:00

(hint) my code:

   $("input").live('dblclick', function(){
    var type12 = $(this).val();
    if (type12.length == 4){
    var time = type12.replace(/\:/, '');
    var hh = time.substr(0,1);
    var mm = time.substr(0,3); // TO DO
    var type24 = Number(hh) + 12;
    var time24 = hh + mm;
    $(this).val(time24);
    sortTimes($(this).closest("tr"));
    }else{alert('not');}
});

Upvotes: 1

Views: 1025

Answers (2)

Jeemusu
Jeemusu

Reputation: 10533

As per my comment, here is what I would do. First of all you should really define a consistent string for your 12 hour time. I would use the format hh:mm am / hh:mm pm.

Secondly, I would ditch the .live() for two reason, firstly, because as of jQuery 1.7 it has been depreciated and replaced by .on(), and secondly because your going to need to have functionality to convert the 24 hour time back to a 12 hour time when the button is double clicked a second time. If you were using single clicks we could use a .toggle(), however for double clicks we will need to use a plugin, and I would recommend using the jQuery-Function-Toggle-Plugin. Once included in your code it can be used like so:

$('input').funcToggle('dblclick', function() {
    //Odd Click
}, function() {
    // Even Click
});

Next, instead of using substrings, which while perfectly fine, we could just use .indexOf(":"), to check if the string has a : in it, and then .split(":") to split the string into an array. This is how I did it:

var type12 = "12:45";
if (type12.indexOf(":") != -1) {
    time_array = type12.split(":");
    hh = time_array[0];  //12
    mm = time_array[1];  //45
}

Full code and example can be found here --> http://jsfiddle.net/374xN/4/

This is probably overkill for what you asked, but hopefully it will point you in the right direction.

Upvotes: 1

Abudayah
Abudayah

Reputation: 3875

here is the answer

   $("input").live('dblclick', function(){
    var type12 = $(this).val();
    if (type12.length == 4){
        var time = type12.replace(/\:/, '');
        var hh = time.substr(0,1);
        var mm = time.substr(1,2);
        var hh = Number(hh) + 12;
        var time24 = hh + ':' + mm;
        $(this).val(time24);
    }else if(type12.length == 5 && type12.substr(0,1) == 0) {
        var time = type12.replace(/\:/, '');
        var hh = time.substr(0,2);
        var mm = time.substr(2,2);
        var hh = Number(hh) + 12;
        var time24 = hh + ':' + mm;
        $(this).val(time24);
    }
});

Upvotes: 1

Related Questions