Format time in angular js filter

20,554

Solution 1

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

Solution 2

See the documentation.

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

Besides I think the format of your date is wrong. Because

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

Example: 1288323623006. So your format is not recognizable for the filter. Try:

$scope.date = new Date();

If you want to convert a string in your given 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 the filter.

Share:
20,554
AlexFF1
Author by

AlexFF1

Full Stack Web, ASP.net, Angular Developer. BSc in Software Systems Development. Waterford. Ireland.

Updated on July 17, 2022

Comments

  • AlexFF1
    AlexFF1 almost 2 years

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

    Have tried

    $scope.date = '06:31:04';
    
    <p ng-bind="date | date:'HH:mm'"></p>
    

    but time not formatting

    How should I make it, thanks

  • AlexFF1
    AlexFF1 almost 9 years
    have applied to my code $scope.date = '06:31:04'; <p ng-bind="date | date:"h:mma"></p> still getting '06:31:04'
  • AlexFF1
    AlexFF1 almost 9 years
    thank you, yes it work with a new date. But i have output in this format 06:31:04, is there a way to reformat this?
  • Ulises Vargas De Sousa
    Ulises Vargas De Sousa over 7 years
    This works perfect to me, but in return $filter('date')(date, 'h:mm') I turn for return $filter('date')(date, 'h:mm a')