2

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

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.

1
  • Whelp, took a few edits and re-reading a few things, but I found a way to do it. Commented Aug 3, 2016 at 23:05

1 Answer 1

2

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:

app.run(['$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:

var MY_DATETIME_FILTERS = {
    'paddedShortDate': 'MM/dd/yy'
};

app.filter('myFormat', ['$filter', function($filter) {
    return function(format) {
        return $filter('date')(input, MY_DATETIME_FILTERS[format] || format);
    }
}]);
Sign up to request clarification or add additional context in comments.

1 Comment

Small correction to answer for any future visitors to this page: return function(input, format) { return $filter('date')(input, MY_DATETIME_FILTERS[format] || format); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.