带有unix时间戳的ui bootstrap datepicker

Fra*_*ain 5 angularjs angular-ui-bootstrap

我正在尝试使用ui-bootstrap datepicker绑定到unix时间戳数据.

为此,我想使用这个指令将unix时间戳转换为ng-model的javascript日期.

这是代码(plunker)

<div ng-model="date" date-format>
    <datepicker min="minDate" show-weeks="false"></datepicker>
</div>
Run Code Online (Sandbox Code Playgroud)

和指令

  .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 "";
                    });
              }
        };
  })
Run Code Online (Sandbox Code Playgroud)

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

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

小智 0

你不需要乘法和除法

link: function(scope, element, attr, ngModelCtrl) {
          ngModelCtrl.$formatters.unshift(function(timestamp) {
            if (timestamp) {
              var date = new Date( timestamp );
              console.log('timestamp to date: ', date); 
              return date;
            }   else return "";
          });
          ngModelCtrl.$parsers.push(function(date) {
            if (date instanceof Date) {
              timestamp = date.getTime();
              console.log('date to timestamp: ', timestamp);
              return timestamp; 
                } else return "";
          });
        }
Run Code Online (Sandbox Code Playgroud)