2016-03-06 57 views
0

美好的一天,默认情况下,我在使用momentjs的ui bootstrap datepicker输入字段中以这种格式设置日期,如YYYY-MM-DD。日期以我希望的格式正确显示。当我选择不同的日期时,它会正确显示输入字段,但是当我决定控制台日志时,会将一天中的值添加到该日志中并且带有时区(T00:00:00.000Z)。这里是我的htmlangularjs ui bootstrap datepicker意外地增加了一天

<div class="row"> 
       <div class="col-md-6"> 
        <label>Drawdown Ent. Date <span style="color: red;">*</span></label> 
        <input type="text" 
          class="form-control" 
          datepicker-popup="yyyy-MM-dd" 
          ng-model="bookloan.drawdown_ent_date" 
          is-open="drawdown_ent_date.open" 
          ng-click="drawdown_ent_date.open = true" 
          datepicker-options="entDateOptions" 
          date-disabled="disabled(date, mode)" 
          close-text="Close" /> 
       </div> 
      </div> 

这里的一个片段是我的JavaScript代码SNIPPIT:

$scope.bookloan.drawdown_ent_date = moment().format("YYYY-MM-DD"); 

这是什么原因?在此先感谢..

+0

我已经创建了一个Plunker,不使用moment.js(http://plnkr.co/edit/ZH7SD940lL2TXaUuHdVc?p=preview),并且日期选择器更改时,观察器显示正确的日期。 –

+0

另外,'$ scope.dt = moment().format(“YYYY-MM-DD”);'给出错误。 –

回答

1

我找到了解决我的问题,通过使用这个指令:

app.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.toISOString().substring(0, 10); 
     }); 

     // 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; 
     }); 
    } 
}]); 

,并放置在输入元素指令名:

<div class="col-md-6"> 
        <label>Drawdown Ent. Date <span style="color: red;">*</span></label> 
        <input type="text" 
          class="form-control" 
          datepicker-local-date 
          datepicker-popup="yyyy-MM-dd" 
          ng-model="bookloan.drawdown_ent_date" 
          is-open="drawdown_ent_date.open" 
          ng-click="drawdown_ent_date.open = true" 
          datepicker-options="entDateOptions" 
          date-disabled="disabled(date, mode)" 
          close-text="Close" /> 
       </div> 
      </div>