Search code examples
javascriptangularjstimeecmascript-5

Transform 12h clock values to 24h clock values


Given a number of strings that contain clock values such as "12.00 am - 4.00 pm", "4.00 - 9.00 am" and "5.00 am - 9.00 am, 1.00 - 8.00 pm", how can I transform each of them into their 24h equivalent, in this case "12:00-16:00", "4.00-9.00" and "5.00-9.00, 13.00-20.00"?


Solution

  • var str = "12.00 am - 4.00 pm\n4.00 - 9.00 am\n5.00 am - 9.00 am\n1.00 - 8.00 pm";
    var reg = /(\d+\.\d+)( am| pm|)? - (\d+\.\d+) (am|pm)/g;
    str.replace(reg,function myfun(g,g1,g2,g3,g4){
        if(!g2){
            g2 = g4
        }
        if(g2=='pm'){
            g1 = (parseInt(g1)+12)+".00";
        }
        if(g4=='pm'){
            g3 = (parseInt(g3)+12)+".00";
        }
        return g1+" - "+g3;
    });
    

    I tried it with javascript and regex.

    Result:
        12.00 - 16.00
        4.00 - 9.00
        5.00 - 9.00
        13.00 - 20.00