Why does angularjs bootstrap datepicker pick one day before?

我只是一个虾纸丫 提交于 2019-12-05 15:57:16
Antiga

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

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!