Skip to content

Instantly share code, notes, and snippets.

@mohsinrasool
Created July 26, 2015 11:16
Show Gist options
  • Save mohsinrasool/957ca23aa7527eb6d5d3 to your computer and use it in GitHub Desktop.
Save mohsinrasool/957ca23aa7527eb6d5d3 to your computer and use it in GitHub Desktop.
/** Angular JS datepicker fix for mssql dates
*
*/
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) {
// 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);
}
else
return '';
});
// 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());
if(dt.getYear() == 0) {
return undefined;
}
if($(element).hasClass('datetime')) {
return dt.format('YYYY/MM/DD hh:mm');
}
else if($(element).hasClass('time')) {
return dt.format('hh:mm');
}
else
return dt.format('YYYY/MM/DD');
});
}
// function format(format) {
// // set default format if function argument not provided
// format = format || 'YYYY-MM-DD hh:mm';
// var zeropad = function(number, length) {
// number = number.toString();
// length = length || 2;
// while(number.length < length)
// number = '0' + number;
// return number;
// },
// // here you can define your formats
// formats = {
// YYYY: this.getFullYear(),
// MM: zeropad(this.getMonth() + 1),
// DD: zeropad(this.getDate()),
// hh: zeropad(this.getHours()),
// mm: zeropad(this.getMinutes())
// },
// pattern = '(' + Object.keys(formats).join(')|(') + ')';
// return format.replace(new RegExp(pattern, 'g'), function(match) {
// return formats[match];
// });
// };
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment