如何将0200,0900,1600时间转换为AM和PM

时间:2018-11-12 22:19:47

标签: javascript angularjs

我有下面的时间代码,但是..当用户我的用户输入0800 , 1600 ,0230时 像这个时候如何隐瞒这次到上午和下午

function tConv24(time24) {
  var ts = time24;
  var H = +ts.substr(0, 2);
  var h = (H % 12) || 12;
  h = (h < 10)?("0"+h):h;  // leading 0 at the left for 1 digit hours
  var ampm = H < 12 ? " AM" : " PM";
  ts = h + ts.substr(2, 3) + ampm;
  return ts;
};

console.log(tConv24('0200'));
console.log(tConv24('0900'));
console.log(tConv24('1600'));

2 个答案:

答案 0 :(得分:2)

一个普通的JavaScript函数可能看起来像这样,仅执行文本处理:

function f(s) {
  var m = s.match(/^(\d\d)(\d\d)$/)
  if (!m) { return null }
  var hour = Number(m[1])
  if (hour < 12) {
    return `${hour}:${m[2]} AM`
  }
  return `${hour-12}:${m[2]} PM`
}

f('0800') // => "8:00 AM"
f('1630') // => "4:30 PM"
f('foo')  // => null

由于您使用的是AngularJS,因此可以包装现有的date过滤器并使用其格式化程序,如下所示:

myAngularModule
  .filter('t24', function($filter) {
    return function(input) {
      var m;
      if (m = input.match(/^(\d\d)(\d\d)$/)) {
        var now = new Date()
        now.setHours(m[1])
        now.setMinutes(m[2])
        return $filter('date')(now, 'hh:mm a')
      }
      return 'invalid time'
    }
  })

...
<div>
  You chose {{ theUserTime | t24 }}
</div>

答案 1 :(得分:0)

function tConv24(time24) {
  var ts = time24;
  console.log(ts);
  var H = +ts.substr(0, 2);
  var h = (H % 12) || 12;
  h = (h < 10)?("0"+h):h;  // leading 0 at the left for 1 digit hours
  var ampm = H < 12 ? " AM" : " PM";
  ts = h + ':' + ts.substr(2, 3) + ampm;
  return ts;
};

console.log(tConv24('0800'));
console.log(tConv24('1034'));
console.log(tConv24('0000'));
console.log(tConv24('1200'));
console.log(tConv24('2222'));
console.log(tConv24('2359'));