【问题标题】:angularJs directive to format dateangularJs 指令格式化日期
【发布时间】:2014-04-20 07:43:47
【问题描述】:

我希望有一个角度功能,它有助于输入日期并以正确的格式显示它,并且不允许其中包含无效值。还能够显示服务器返回的 '20140314T00:00:00Z' json 字符串作为日期。

谁能帮帮我?

【问题讨论】:

    标签: angularjs date format


    【解决方案1】:

    Angular.js 已经有日期过滤器{{20140314 | date}} // Jan 1, 1970 9:35:40 AM

    Angular Date Docs

    【讨论】:

    【解决方案2】:

    这对我有用,

       .directive('myDate', ['$timeout', '$filter', function ($timeout, $filter)
        {
            return {
                require: 'ngModel',
    
                link: function ($scope, $element, $attrs, $ctrl)
                {
                    var dateFormat = 'mm/dd/yyyy';
                    $ctrl.$parsers.push(function (viewValue)
                    {
                        //convert string input into moment data model
                        var pDate = Date.parse(viewValue);
                        if (isNaN(pDate) === false) {
                            return new Date(pDate);
                        }
                        return undefined;
    
                    });
                    $ctrl.$formatters.push(function (modelValue)
                    {
                        var pDate = Date.parse(modelValue);
                        if (isNaN(pDate) === false) {
                            return $filter('date')(new Date(pDate), dateFormat);
                        }
                        return undefined;
                    });
                    $element.on('blur', function ()
                    {
                        var pDate = Date.parse($ctrl.$modelValue);
                        if (isNaN(pDate) === true) {
                            $ctrl.$setViewValue(null);
                            $ctrl.$render();
                        } else {
                            if ($element.val() !== $filter('date')(new Date(pDate), dateFormat)) {
                                $ctrl.$setViewValue($filter('date')(new Date(pDate), dateFormat));
                                $ctrl.$render();
                            }
                        }
    
                    });
                    $timeout(function ()
                    {
                        $element.kendoDatePicker({
    
                            format: dateFormat
                        });
    
                    });
                }
            };
        }])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-21
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-10
      相关资源
      最近更新 更多