添加新格式的角度日期过滤器?

时间:2023-02-01 11:17:45

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

例如,我现在可以这样做:{{myScope。日期:'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.

我想做的是:{myScope。时间戳|日期:'paddedShortDate'},它将强制将单个数字的日期部分添加到前面的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 个解决方案

#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:

查看这里的源代码,DATE_FORMATS是从$locale获取的。虽然我不建议编辑这些(作为$locale)。DATE_FORMATS是一个私有的API,将来可以改变),你应该可以通过运行块来实现:

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);
    }
}]);

#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:

查看这里的源代码,DATE_FORMATS是从$locale获取的。虽然我不建议编辑这些(作为$locale)。DATE_FORMATS是一个私有的API,将来可以改变),你应该可以通过运行块来实现:

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);
    }
}]);