Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set an AngularJS date filter format to be used by all references to the date filter?

Tags:

Rather that having to define a custom format for each call to the date filter, is there a way to globally define a default format (other than 'medium')?

I would like to have the format set in one file rather than all over the place in my code (the date format may end up being changed in the future and a modification in one file would be much nicer than having to make changes in many files).

This is what I am doing now (defining date format each time):

{{systemTime | date:'dd MMMM @ HH:mm:ss'}}
{{modifiedTime | date:'dd MMMM @ HH:mm:ss'}}
{{getShippedTime() | date:'dd MMMM @ HH:mm:ss'}}
   etc.

I was thinking of creating a custom filter (let's call it myDate), which would act as a wrapper and then pass off the date string to the Angular date filter with my custom format, so then my code could just look like this:

{{systemTime | myDate}}
{{modifiedTime | myDate}}
{{getShippedTime() | myDate}}
   etc.

However, I can't figure out how to make the myDate filter point to the Angular date filter.

Thanks for your help.

like image 275
Kabb5 Avatar asked Aug 22 '13 19:08

Kabb5


People also ask

Is date a filter in AngularJS?

AngularJS date filter is used to convert a date into a specified format. When the date format is not specified, the default date format is 'MMM d, yyyy'. Parameter Values: The date filter contains format and timezone parameters which is optional.

Which date format will output as string in AngularJS?

Arguments. 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.

What is the date format in angular?

The date filter formats a date to a specified format. By default, the format is "MMM d, y" (Jan 5, 2016).

What is the correct way to apply filter in AngularJS?

In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for the filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.


1 Answers

Based on some more research and then considering the comment by moderndegree, I have found that the following myDate filter will work:

.filter('myDate', function($filter) {    
    var angularDateFilter = $filter('date');
    return function(theDate) {
       return angularDateFilter(theDate, 'dd MMMM @ HH:mm:ss');
    }
});
like image 121
Kabb5 Avatar answered Sep 27 '22 21:09

Kabb5