-1

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"?

Soggiorno
  • 760
  • 9
  • 17
  • this shouldn't be terribly difficult if you know a little [modulo math](https://en.wikipedia.org/wiki/Modulo_operation). You definitely need to show some effort though. – kaveman Jul 03 '15 at 02:05
  • Have you tried searching already? This may lead you in the correct direction: http://stackoverflow.com/questions/15083548/convert-12-hour-hhmm-am-pm-to-24-hour-hhmm – leemac Jul 03 '15 at 02:13
  • I tried dividing the array into different parts using substring and indexOf, then adding 12 if the extension is pm. The problem is that the format is not always the same so the parts get messed up. I also can't target the "-" character with indexOf since it is some special sort. – Soggiorno Jul 03 '15 at 02:17

1 Answers1

0
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
Kerwin
  • 1,212
  • 1
  • 7
  • 14