Angular Bootstrap DatePicker UTC 错误输出

Angular Bootstrap DatePicker UTC wrong output

您好,我在我的应用程序中使用 Angular DatePicker,它按预期工作。我尝试使用 UTC 时间,并且 datepicker 是用这个值初始化的:

scope.model.value = moment.utc().startOf('day').toDate()

这个日期的结果:

Tue Oct 27 2015 01:00:00 GMT+0100 (Mitteleuropäische Zeit)

如果我想现在选择一个日期,例如:2016 年 6 月 1 日,scope.model.value 的结果是:

"2016-05-31T23:00:00.000Z"

为什么我的 DatePicker 将我的日期对象更改为另一种格式? 我该如何处理输出格式?为什么选择 6 月 1 日时日期是 5 月 31 日?

我尝试了多种方法,例如删除 UTC 时间信息。例如: (https://gist.github.com/weberste/354a3f0a9ea58e0ea0de):

(function () {
'use strict';
 angular
.module('myApp')
.directive('datepickerLocaldate', ['$parse', function ($parse) {
  var directive = {
    restrict: 'A',
    require: ['ngModel'],
    link: link
  };
  return directive;

  function link(scope, element, attr, ctrls) {
    var ngModelController = ctrls[0];

    // called with a JavaScript Date object when picked from the datepicker
    ngModelController.$parsers.push(function (viewValue) {
      // undo the timezone adjustment we did during the formatting
      viewValue.setMinutes(viewValue.getMinutes() - viewValue.getTimezoneOffset());
      // we just want a local date in ISO format
      return viewValue;
    });

    // called with a 'yyyy-mm-dd' string to format
    ngModelController.$formatters.push(function (modelValue) {
      if (!modelValue) {
        return undefined;
      }
      // date constructor will apply timezone deviations from UTC (i.e. if locale is behind UTC 'dt' will be one day behind)
      var dt = new Date(modelValue);
      // 'undo' the timezone offset again (so we end up on the original date again)
      dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
      return dt;
    });
  }
}])
})

对于那些喜欢这里的人来说,我是如何使用选择器的片段:

<datepicker datepicker-localdate ng-model="model.value" min-date="minDate"></datepicker>

也许有人可以提供帮助!

在您的应用配置中,您可以在全局范围内告知您希望 dapicker 输出格式如何。例如:

datepickerPopupConfig.datepickerPopup = 'dd/MM/yyyy';

文档在这里:angular boostrap datepicker DOC

鉴于您的应用名称是 "myapp":

angular.module('myapp', [
    'ui.bootstrap'
])
.config(function(
        datepickerPopupConfig
    ) {

        datepickerPopupConfig.datepickerPopup = 'dd/MM/yyyy';

    }
);

所以日历问题的解决方法是:

function apply() {
    // create new UTC date object
    // necessary to prevent usage of browser timezone which results in selection of previous day in some cases
    if (scope.model.type === 'calendar') {
      var date = moment(scope.model.value);
      scope.model.value = new Date(Date.UTC(date.format('YYYY'), date.format('MM')-1, date.format('DD')));
    }

希望这可以帮助其他人解决这个问题!

此致