Why does angularjs bootstrap datepicker pick one d

2019-05-07 18:49发布

I'm using angularjs bootstrap datepicker directive and when I set a date from model it picks a day before the selected date.

<button type="button" class="btn btn-sm btn-default" ng-click="dt = '2014-09-24'">2014-09-24</button>

Here is a plunk with the issue.

Is there any solution?

4条回答
狗以群分
2楼-- · 2019-05-07 19:35

I just initialized the ngModel with new Date(), and the date was set correctly thereafter, even after I changed it with the date picker !

查看更多
不美不萌又怎样
3楼-- · 2019-05-07 19:39

This is due to the way JS handles dates natively. AngularUI team mentions this in the docs.

Here's one solution: Angular-UI One day is subtracted from date in ui-date

查看更多
ら.Afraid
4楼-- · 2019-05-07 19:39

my solution is to use a directive to fix the minus 1 issue, and also to format the view and model values:

app.directive('ngBootstrapFix',['$filter', function($filter) {
  return {
    require: 'ngModel',
    priority: 1,
    link: function($scope, $element, $attrs, ngModelCtrl) {
      ngModelCtrl.$parsers.push(function(viewValue) {
        viewValue = $filter('date')(viewValue, 'yyyy-MM-dd');
        return viewValue;
      });
      ngModelCtrl.$render = function() {
        var val = $filter('date')(ngModelCtrl.$viewValue, 'dd/MM/yyyy');
        $element.val(val);
      };
    }
  };
}]);
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-05-07 19:51

For anyone needing a solution in the .NET Web Api world, this line worked well for me:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;

It was due to the JsonFormatter spitting out the time in the wrong time zone.

查看更多
登录 后发表回答