Skip to content

Instantly share code, notes, and snippets.

@dprothero
Forked from nsilvah/gist:a7a31f017de098a79f38
Last active September 9, 2015 18:51
Show Gist options
  • Save dprothero/224a4752faa6c1797526 to your computer and use it in GitHub Desktop.
Save dprothero/224a4752faa6c1797526 to your computer and use it in GitHub Desktop.
DatePicker directive to fix timezone issues
app.directive('datepickerLocaldate', [function () {
var directive = {
require: 'ngModel',
link: link
};
return directive;
function link(scope, element, attr, ngModel) {
scope.$watch(
function(){
return ngModel.$modelValue;
},
function(modelValue){
if (modelValue && !(modelValue instanceof Date)) {
var dt = new Date(modelValue);
if(dt.getTimezoneOffset() > 0)
dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
ngModel.$modelValue = dt;
ngModel.$render();
}
});
}
}]);
@dprothero
Copy link
Author

I find this works better than just doing the conversion on the first pass. This handles two additional cases that the original gist did not:

  1. The modelValue starts off as null and then the user selects a date (which is a valid Date and doesn't need conversion).
  2. The modelValue gets re-populated with data from the service call (or whatever was populating the date string without timezone info).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment