format time 12 to 24 hours - javascript

This code will return 24 hours time format form 12 hours
function format12to24(time) {
    var t = time;
    if (!t) { return null; }
    var arr = t.split(":");
    var h = parseInt(arr[0]);
    if (t.includes("pm")) {
        var nH = h != 12 ? h + 12 : h;
        var t = t.replace(hnH);
    }
    else {
        var nH = h != 12 ? h : h - 12;
        var t = t.replace(hnH);
    }
    t = t.split(" ")[0];
    console.log(t);
    return t;
}
//To run a test using console
console.time("start");
console.log("6:24 pm");
format12to24("6:24 pm");
console.timeEnd("start");
//Test 2
console.log("6:24 am");
format12to24("6:24 am");

//Test 3
console.log("12:24 pm");
format12to24("12:24 pm");

//Test 4
console.log("12:24 am");
format12to24("12:24 am");

//Test 5
console.log("1:24 am");
format12to24("1:24 am");


//Test 6
console.log("1:24 pm");
format12to24("1:24 pm");

This function takes a parameter in string that must be time type in string format.
When you pass for example 1:24 pm in string it will convert this into 24hours format that will be 13:24 

Approach

1. Pass argument with time formatted.
2. If argument is invalid i.e empty ,null or undefined then  return null.
3. Now split time string with split function of string with : seperator and store in arr variable.
4. At position 0 of arr variable which is an array type have hours and at 1 position minutes parse this in number and store in h variable
5. Check time variable contains pm if yes then check h not equal to 12 if true then add 12 to hour variable h else return h and store this value in nH variable which is new hour value
6. If time variable contains am which is else part check again h value is not equal to 12 if true the return h else subtract 12 from h.
7. At 5 and 6 step we replacing h value with nH and assign to t variable which holding value of time variable.
8. Finally split t value with space and get position 0 element then store to t variable so this will show 24 hours format.

In code there are some test case you can use them with console to test the code.

You can try this by yourself and try to achieve this with different approaches this will increase your programming skills as well as thinking power.



Comments