I'm using KnockoutJS with the mapping plugin and all is working well, apart from a DateTime field which is serialized as ticks like so: /Date(x)/ where x = ticks.
How would I: 1) Parse the date object into human readable form? 2) Return this out from the custom binding back into the value in the model?
I'm using KnockoutJS with the mapping plugin and all is working well, apart from a DateTime field which is serialized as ticks like so: /Date(x)/ where x = ticks.
How would I: 1) Parse the date object into human readable form? 2) Return this out from the custom binding back into the value in the model?
Share Improve this question edited Oct 23, 2013 at 15:05 rae1 6,1445 gold badges28 silver badges49 bronze badges asked May 10, 2011 at 16:26 jaffajaffa 27.4k51 gold badges180 silver badges293 bronze badges 2- Did you read this: stackoverflow.com/questions/5942789/… – mplungjan Commented May 10, 2011 at 18:22
- Yes, not sure how it would help me though. I'm wondering whether to format the date as a string represented in the model. Thoughts? – jaffa Commented May 11, 2011 at 15:11
3 Answers
Reset to default 14Here's an example of a custom binding in knockoutjs. It uses moment.js to parse the date
ko.bindingHandlers.date = {
update: function (element, valueAccessor) {
var value = valueAccessor();
var date = moment(value);
$(element).text(date.format("L"));
}
};
In your javascript you can then use the new binding like any other knockout binding.
<td data-bind="date:Created" />
I don't know anything about KnockoutJS, so there may be a better way of doing this that's already built-in. I also don't know anything about the second question. Hopefully someone who actually knows something about it can help you.
So, with that disclaimer, here's how you can convert it using "plain" JavaScript (you might need to include Douglas Crockford's json2.js if you want to support "old" browsers). JSON.parse
takes an optional reviver
argument that can replace each value as it's parsed.
JSON.parse(jsonText, function(key, value) {
// Check for the /Date(x)/ pattern
var match = /\/Date\((-?\d+)\)\//.exec(value);
if (match) {
var date = new Date(+match[1]); // Convert the ticks to a Date object
return humanReadable(date); // Format the date how you want it
}
// Not a date, so return the original value
return value;
});
Here is an example if you have functions in your viewmodel and binding to an input:
ko.bindingHandlers.date = {
update: function (element, valueAccessor) {
var value = valueAccessor();
var date = moment(value());
var strDate = date.format('YYYY-MM-DD');
$(element).val(strDate);
}
};
Link to moment.js