2016-03-06 50 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>