加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 带有unix时间戳的ui bootstrap datepicker

发布时间:2020-12-17 10:21:58 所属栏目:安全 来源:网络整理
导读:我正在尝试使用ui-bootstrap datepicker绑定到unix时间戳数据. 为此,我想使用this directive将unix时间戳转换为ng-model的javascript日期. here is the code (plunker) div ng-model="date" date-format datepicker min="minDate" show-weeks="false"/datepi
我正在尝试使用ui-bootstrap datepicker绑定到unix时间戳数据.

为此,我想使用this directive将unix时间戳转换为ng-model的javascript日期.

here is the code (plunker)

<div ng-model="date" date-format>
    <datepicker min="minDate" show-weeks="false"></datepicker>
</div>

和指令

.directive('dateFormat',function() {
        return {
              require: 'ngModel',link: function(scope,element,attr,ngModelCtrl) {
                    ngModelCtrl.$formatters.unshift(function(timestamp) {
                          if (timestamp) return new Date( timestamp * 1000 );
                          else return "";
                    });
                    ngModelCtrl.$parsers.push(function(date) {
                          if (date instanceof Date) return Math.floor( date.getTime() / 1000 ); 
                          else return "";
                    });
              }
        };
  })

可以选择日期. unix时间戳是正确的但是,日历切换到1970 …

是否有解决方案使这项工作和使用ui bootstrap的datepicker与unix时间戳数据?

这有点晚了,但我也有这个问题 – 我不想在我的模型中为datepicker / timepicker保留额外的价值.跟随Christopher Nadeau跟随 this great tutorial on ngModelController

这适用于AngularJS 1.2.16:

.directive('timestampFormat',function() {
    // Directive that converts timestamp back and forth from
    // seconds to Date object
    return {
        scope: true,// isolated scope
        require: 'ngModel',ngModelCtrl) {

            ngModelCtrl.$formatters.push(function (modelValue) {
                // returns $viewValue
                return {
                    timestamp: (modelValue ? new Date(modelValue*1000) : "")
                };
            });

            scope.$watch('timestamp',function () {
                ngModelCtrl.$setViewValue({ timestamp: scope.timestamp });
            });

            ngModelCtrl.$parsers.push(function (viewValue) {
                // returns $modelValue
                if (viewValue.timestamp instanceof Date) return Math.floor( viewValue.timestamp.getTime() / 1000 );
                else return "";
            });

            ngModelCtrl.$render = function () {
                // renders timestamp to the view.
                if (!ngModelCtrl.$viewValue) ngModelCtrl.$viewValue = { timestamp: ""};
                scope.timestamp = ngModelCtrl.$viewValue.timestamp;
            };
        }
    };
});

现在,您可以将其作为时间戳变量访问.

<div ng-model="yourModelValue" timestamp-format> 
  {{timestamp}}
  <timepicker ng-model="timestamp" ...>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读