【问题标题】:Not able to apply angular js built in filter for date无法为日期应用内置过滤器的角度 js
【发布时间】:2016-04-02 03:37:07
【问题描述】:

我的范围变量以这种格式保存日期:

$scope.thisDay="2016-01-01 00:00:01"

{{thisDay}} --->2016-01-01 00:00:01

我为上述应用了日期过滤器,例如:

{{thisDay | date:'medium'}}

但这似乎不适用于我的情况。 关于上述的任何建议...

【问题讨论】:

    标签: javascript angularjs date angularjs-filter


    【解决方案1】:

    Date 过滤器需要日期类型的数据,但您提供的是字符串而不是日期。

    这样试试

    $scope.thisDay=new Date("2016-01-01 00:00:01");
    

    JSFIDDLE

    如果您不想在范围内转换日期

    然后创建一个过滤器,它将您的字符串转换为日期对象

    myApp.filter('convert2date', function() {
      return function(input) {
        return input ? new Date(input) : "";
      };
    });
    

    将它添加到您的 html

     {{thisDay | convert2date |date:'medium'}}
    

    JSFIDDLE

    【讨论】:

    • 我想直接在html中进行修改
    • 我的小提琴结果为空
    【解决方案2】:

    根据Date filter documentationdate 参数应该是:

    日期格式化为日期对象,毫秒(字符串或数字) 或各种 ISO 8601 日期时间字符串格式(例如 yyyy-MM-ddTHH:mm:ss.sssZ 及其较短的版本,如 yyyy-MM-ddTHH:mmZ、yyyy-MM-dd 或 yyyyMMddTHHmmssZ)。如果没有时区 在字符串输入中指定的时间被认为是在 当地时区。

    因此,您需要将字符串转换为有效的 javascript 日期,或者创建自己的过滤器,该过滤器依赖于 angularjs 内置的日期过滤器

    angular.module('app').filter('customDateFormat', function($filter) {
        return function(value) {
            if (value == null) {
                return "";
            }
            return $filter('date')(new Date(value).toISOString(), 'medium');
        };
    });
    

    然后在你的 html 中, {{ thisDay | customDateFormat}}

    更新:

    此外,如果您想让您的过滤器更通用,并且将日期格式与您的日期一起传递,该怎么办:

    angular.module('app').filter('customDate', function($filter) {
        return function(value, format, defaultValue) {
            if (value == null) {
                if (defaultValue) {
                    return defaultValue;
                } else {
                    return "";
                }
            }
            return $filter('date')(new Date(value).toISOString(), format);
        };
    });
    

    然后在你的 HTML 中:

    {{thisDay | customDateFormat:'shortTime'}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      相关资源
      最近更新 更多