Angular 日期过滤器不适用于毫秒(字符串或数字)

Angular date filter not working with milliseconds (string or number)

我的观点是这样的:

{{1288323623006 | date:'%d/%m/%Y %I:%M:%S %p'}}

但是它在我的控制台中抛出一个错误,如下所示:

当我将毫秒转换为控制器中的日期对象时,如下所示:

$scope.myDate = new Date(1288323623006);

在我看来:

{{myDate  | date:'%d/%m/%Y %I:%M:%S %p'}}

然后它按预期显示 29/10/2010 06:40:23 AM

这是 Angular Docs 中的一个示例,它在我的控制台中引发了上述错误。

我可以将日期转换为对象并将其传递给视图,但我有兴趣以这种方式管理它,因为我不想使用这样的修复程序。

我的 I18nAdapter.

中没有任何更改

有人遇到过类似的问题吗?

因为您正在尝试解析非日期对象。您需要将 Date 对象传递给过滤器,就像您在控制器中所做的那样。你应该这样做:

{{new Date(1288323623006) | date:'%d/%m/%Y %I:%M:%S %p'}}

您可以创建一个自定义过滤器并将其与您的值一起使用,如下所示:

过滤器:

.filter('millisecondsToDate', function($filter) {
  return function(millseconds) {
    var timeString = $filter('date')(new Date(millseconds),'d/M/yyyy HH:mm:ss a');
    return timeString;
  };
})

HTML:

{{ 1288323623006 | millisecondsToDate }}

这将输出 29/10/2010 06:40:23 AM.

编辑:

其实这个也行:

{{ 1288323623006 | date: 'd/M/yyyy HH:mm:ss a' }}

所以您的日期格式有误,这就是为什么 Angular 无法将其转换为日期的原因。

请参阅 documentation for AngularJS date 了解正确的格式。

这是一个 JSFiddle:https://jsfiddle.net/thepio/qrr451pk/

编辑 2:

使用 i18n 您尝试过以下方法吗?

{{ 1288323623006 | date:'short'}}

或使用自定义格式:

{{ 1288323623006 | date:'d/M/yy h:mm:ss a' }}

我最近解决了这个问题,现在我发布我的解决方案。

事实证明 angular 的过滤器不起作用,因为使用了本地化的过滤器。

我所做的是通过在我们的 i18n.js 库中注释这些行来禁用本地化日期过滤器:

angular.module('app.filters.I18nAngular', []).filter('translate', function() {
   return function(key, obj) {
      return i18nAdapter.translate(key, obj);
   };
}).filter('number', function() {
   return function(value, options) {
      return i18nAdapter.formatNumber(value, options);
   };
}).filter('currency', function() {
   return function(value) {
      return i18nAdapter.formatCurrency(value);
   };
});
// .filter('date', function() {
// return function(value, format) {
// return i18nAdapter.formatDate(value, format);
// };
// });

i18nAdapter 有自己的格式和过滤器,类似于 angular,但在我们的例子中,我们可以使用 angular 提供的格式和过滤器。