Skip to content

Instantly share code, notes, and snippets.

@groovenectar
Created June 3, 2021 06:53
Show Gist options
  • Save groovenectar/3ad953abbd52b357ca4ede52cc4dbca9 to your computer and use it in GitHub Desktop.
Save groovenectar/3ad953abbd52b357ca4ede52cc4dbca9 to your computer and use it in GitHub Desktop.
Date Binding for Knoockout JS
ko.bindingHandlers.date = {
update: function(element, valueAccessor) {
// First get the latest data that we're bound to
let data = valueAccessor();
// Next, whether or not the supplied model property is observable, get its current value
let value = ko.unwrap(data);
let prop = element.nodeName === 'INPUT' ? 'value' : 'innerText';
if (value instanceof Date) {
if (element.type === 'date') {
element[prop] = value.toISOString().split('T')[0];
}
if (element.type === 'time') {
element[prop] = value.getHours().toString().padStart(2, '0') + ':' + value.getMinutes().toString().padStart(2, '0');
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment