最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert 24 hours time variable into 12Hours time with AngularJSjQuery - Stack Overflow

programmeradmin3浏览0评论

I'm getting a value from database which is in 24 hours time string. I'm looking for a way to change this string in to 12 hours clock time using angularJS or jQuery.

I can not do any code changes to the back-end(JAVA) or database at the moment.

var offTime = "17:25:11";

I need it to display as : "5:25:11"

please help !

I'm getting a value from database which is in 24 hours time string. I'm looking for a way to change this string in to 12 hours clock time using angularJS or jQuery.

I can not do any code changes to the back-end(JAVA) or database at the moment.

var offTime = "17:25:11";

I need it to display as : "5:25:11"

please help !

Share Improve this question asked Apr 24, 2015 at 13:37 Nomesh DeSilvaNomesh DeSilva 1,6494 gold badges26 silver badges43 bronze badges 4
  • 1 I would remend Moment.js – Drew R Commented Apr 24, 2015 at 13:39
  • Me too, and the directive angular-moment : github./urish/angular-moment – Jeremy Thille Commented Apr 24, 2015 at 13:44
  • MomentJs is gourgeous and remended. – katmanco Commented Apr 24, 2015 at 13:46
  • 1 I can not use any additional libraries here guys. only angular and jquery is what I have. – Nomesh DeSilva Commented Apr 24, 2015 at 13:49
Add a ment  | 

3 Answers 3

Reset to default 4

Working off Kabb5's answer I added a bit more logic to determine AM / PM and check for 0 so 0 AM isn't an option.

angular.module('simpleAppFilters').filter('twentyFourToTwelve', function () {
return function (inputTime) {        
    inputTime = inputTime.toString(); //value to string for splitting
    var splitTime = inputTime.split(':');
    var ampm = (splitTime[0] >= 12 ? ' PM' : ' AM'); //determine AM or PM 
    splitTime[0] = splitTime[0] % 12;
    splitTime[0] = (splitTime[0] == 0 ? 12 : splitTime[0] ); //adjust for 0 = 12

    return splitTime.join(':') + ampm;
};
});

You need to split the value by :, the rebuild it after running the first value through the modulo operator. Try this:

var offTime = "17:25:11".split(':');
offTime[0] = offTime[0] % 12;
var output = offTime.join(':');

alert(output);

Create a filter like this:

app.filter('twentyFourToTwelve ', function () {
  return function (inputTime) {
    var splitTime = inputTime.split(':');
    splitTime[0] = splitTime[0] % 12;

    return splitTime.join(':');        
  };
});

And then in your binding:

{{ myTime | twentyFourToTwelve }}
发布评论

评论列表(0)

  1. 暂无评论