Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SandeepThomas/78f2de3f0f8f21869f91 to your computer and use it in GitHub Desktop.
Save SandeepThomas/78f2de3f0f8f21869f91 to your computer and use it in GitHub Desktop.
Dates only with Angular-UI Bootstrap datepicker - In Epoch time / Unix time
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) {
if (!viewValue) {
return undefined;
}
// undo the timezone adjustment we did during the formatting
viewValue.setMinutes(viewValue.getMinutes() - viewValue.getTimezoneOffset());
// we want date in Unix timestamp
return Math.round(new Date(viewValue).getTime() / 1000.0);
});
// called with a Unix timestamp 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 * 1000);
// 'undo' the timezone offset again (so we end up on the original date again)
dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
return dt;
});
}
}]);
@DavidRogersDev
Copy link

@SandeepThomas I've been grappling with the same issue. I have a question. Does the support which the AngularUI Bootstrap Datepicker added for ngModelOptions (specifically the timzone property) replace the need for your directive? Cheers

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