Skip to content

Instantly share code, notes, and snippets.

@mat-mcloughlin
Created August 29, 2013 09:25
Show Gist options
  • Save mat-mcloughlin/6376025 to your computer and use it in GitHub Desktop.
Save mat-mcloughlin/6376025 to your computer and use it in GitHub Desktop.
A knockout binding handler that formats dates correctly. It requires the use of jquery, knockout and moment Ideally I'd do this without jquery
ko.bindingHandlers.date = {
update: function(element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
var allBindings = allBindingsAccessor();
var format = allBindings.format || 'DD/MM/YYYY'; // default format.
if (value && value != 'Invalid Date') {
var formattedDate = moment(value).format(format);
if ($(element).is('input')) {
$(element).val(formattedDate);
} else {
$(element).text(formattedDate);
}
} else {
if ($(element).is('input')) {
$(element).val('');
} else {
$(element).text('');
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment