core core - 2 months ago 5x
Javascript Question

Add new format to Angular date filter?

Is it possible to inject a new shorthand format into the Angular date filter?

For example, I can currently do this:

{{ myScope.timestamp | date: 'shortDate' }}

What I'd like to do is this:
{{ myScope.timestamp | date: 'paddedShortDate' }}
, which would force single-digit date parts to be padded with a leading

I realize I can create my own filter to do this for me—I'm more curious if existing filters are extensive in any manner.


Looking at the source code here, DATE_FORMATS is fetched from $locale. While I wouldn't recommend editing these (As $locale.DATE_FORMATS is a private API, and can change in the future), you should be able to do it via a run block:['$locale', function($locale) {
    $locale.DATETIME_FORMATS.paddedShortDate = 'MM/dd/yy';

As you mentioned, you didn't want to create another filter, but that in my opinion would be the better way to go. A simple filter should work fine:

    'paddedShortDate': 'MM/dd/yy'

app.filter('myFormat', ['$filter', function($filter) {
    return function(format) {
        return $filter('date')(input, MY_DATETIME_FILTERS[format] || format);