Formatting time in angular js filter

How to reformat 06:31:04 time to display only hh: mm - 06:31

Have tried

$scope.date = '06:31:04';

<p ng-bind="date | date:'HH:mm'"></p>

      

but time is not formatting

How can I do this, thanks

+3


source to share


3 answers


The best solution was to write a filter



angular.module('foo', [])
.filter('formatTime', function ($filter) {
return function (time, format) {
    var parts = time.split(':');
    var date = new Date(0, 0, 0, parts[0], parts[1], parts[2]);
    return $filter('date')(date, format || 'h:mm');
};
});




{{ '06:31:04' | formatTime }}

      

+8


source


See the documentation.

<p ng-bind="date | date:"hh:mm"}}></p>

      

Also, I think your date format is wrong. Because

a JavaScript Date instance [...] represents one moment at a time. Date objects are based on a time value, which is the number of milliseconds since January 1, 1970. ( source )

Example: 1288323623006. So your format is not recognized by the filter. Try:



$scope.date = new Date();

      

If you want to convert a string in the specified format to a date, try:

var dateElements = "06:31:04".split(':');
var date = new Date();
date.setHours(time[0]);
date.setMinutes(time[1]);
$scope.date = date;

      

Then you can format it with a filter.

+2


source


u can use the following simple example:

$scope.date=new Date();

      

now in html we have:

    <h2>
        {{ today| date:'hh:mm'  }}
    </h2>

      

0


source







All Articles