将时间字符串(例如上午9:00)转换为24小时(0900)

时间:2013-11-25 09:59:42

标签: javascript regex date-formatting

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;
}

我试图将12小时转换为24小时"军事"时间(即没有冒号)。我在使用正则表达式捕获组和javascript时出现问题,但上面是我认为应该工作的内容。

有人能告诉我正确的方法吗?

1 个答案:

答案 0 :(得分:1)

我认为你错误地报道了正则表达群体......这应该有用。

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];
}