Last active
January 28, 2022 13:47
-
-
Save weberste/354a3f0a9ea58e0ea0de to your computer and use it in GitHub Desktop.
Dates only with Angular-UI Bootstrap datepicker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); | |
} | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The above solutions only work for timezones West of the UTC Timezone. Here's a fix that also works for timezones East of UTC so that dates don't appear one day behind: