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 !

4
  • 1
    I would recommend Moment.js Commented Apr 24, 2015 at 13:39
  • Me too, and the directive angular-moment : github.com/urish/angular-moment Commented Apr 24, 2015 at 13:44
  • MomentJs is gourgeous and recommended. 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. Commented Apr 24, 2015 at 13:49

3 Answers 3

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;
};
});
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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

1 Comment

Thanks, another clean solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.