How to show time with AngularJS date filter

2.4k views Asked by At

I want to show my time as AM and PM, is it possible with angular date filter. I have tried the below code but doesn't work for me.

<div>{{ '12:31:07' | date:'HH:mm' }}</div>
2

There are 2 answers

1
K K On BEST ANSWER

Try a custom filter:

HTML:

<div ng-app>
  <div ng-controller="TodoCtrl">
    <div>{{ '12:31:07' | time }}</div>
  </div>
</div>

JS:

angular.module('myApp').filter('time', ['$filter', function ($filter) {
    return function (input, arg) {
        var parts = input.split(':');
        var date = new Date(0, 0, 0, parts[0], parts[1], parts[2]);
        return $filter('date')(date, arg || 'mediumTime');
    };
}]);

Demo: http://jsfiddle.net/U3pVM/33868/

Or use default filters:

try:

<div>{{ '12:31:07' | date:'mediumTime' }}</div>

or

<div>{{ '12:31:07' | date:'shortTime' }}</div>

You can also try 'medium' or 'short' for date filter

Refer: https://docs.angularjs.org/api/ng/filter/date

0
Kavindra On

According to Angular documentation for date filter, the date argument should be in a valid format.

Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone.

So, you need to format your time string beforehand. For example;

<div>{{ '2017-09-04T12:31:07' | date:'h:mma' }}</div> 

will give you the required result.