简体   繁体   English

使用AngularJS / jQuery将24小时时间变量转换为12小时时间

[英]Convert 24 hours time variable into 12Hours time with AngularJS/jQuery

I'm getting a value from database which is in 24 hours time string. 我从数据库获取一个24小时时间字符串中的值。 I'm looking for a way to change this string in to 12 hours clock time using angularJS or jQuery. 我正在寻找一种使用angularJS或jQuery将字符串更改为12小时制的方法。

I can not do any code changes to the back-end(JAVA) or database at the moment. 目前,我无法对后端(JAVA)或数据库进行任何代码更改。

var offTime = "17:25:11";

I need it to display as : "5:25:11" 我需要将其显示为: "5:25:11"

please help ! 请帮忙 !

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

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. 解决Kabb5的答案时,我添加了更多逻辑来确定AM / PM并检查0,因此0 AM是不可行的。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM