Formatting time in angular js filter
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 to share
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 to share