0
var foo = '1:00 pm'
var bar = to24Hour(foo); //bar would be 1300

function to24Hour(time) {
  time.match('(\d+):(\d+) ([ap]m)');
  if ($1 > 12 && $3 = pm) {
    $1 = 12 + $1;
  }
  return $1.$2;
}

I'm trying to convert 12 hour times to 24 hours "military" time (i.e. no colon). I'm having trouble with regex capture groups and javascript but above is what I think should work.

Can someone show me the correct way?

Stephan
  • 41,764
  • 65
  • 238
  • 329
meiryo
  • 11,157
  • 14
  • 47
  • 52
  • 1
    Isn't there a 'normal way' in javascript to change the date format? – Tafari Nov 25 '13 at 10:03
  • 5
    Why don't you take a look at moment.js? http://momentjs.com/ – This company is turning evil. Nov 25 '13 at 10:04
  • 1
    Are you looking for this: http://jsfiddle.net/aHZYL/ ? Just a quick example. – nkmol Nov 25 '13 at 10:13
  • 1
    You must escape `\d` like this in your regex `\\d+`. The match method returns an array containing the matching groups or `null` if no matches were found. So replace `$1`,`$2` and `$3` respectively with `result[1]`, `result[2]` and `result[3]` where `result` is the array returned by `match`. If you want to perform date formatting, regular expressions are NOT the best bet here. Check this SO answer instead: http://stackoverflow.com/a/1056730/363573 – Stephan Nov 25 '13 at 10:22

1 Answers1

1

I think you misreferensed the regex groups... This should work.

function to24Hour(time) {
  var hour, groups = (/(\d+):(\d+) ([ap]m)/i).exec(time);

  hour = parseInt(groups[1], 10);

  if (hour < 12 && groups[3] === "pm") {
    hour += 12;
  }

  return hour.toString() + groups[2];
}
A. Tapper
  • 1,261
  • 8
  • 17