Asp.net web api is switching to json.net for data serialization, and it seems like everyone has finally decided to support the ISO 8601 date format. Since the json spec itself doesn’t specify a particular dates format, this has historically been quite a mess.
So if you are using knockout.js on the client, then you are likely to run into issues binding ISO 8601 dates to the UI. Unfortunately, using ISO 8601 dates in knockout.js isn’t as straight-forward as it would seem. If you just shove the ISO 8601 data into your viewmodel, you’ll get the raw ISO 8601 string displayed on screen.
This is rarely what you want.
A better solution is to have knockout.js bind the date field to the UI in a human readable and writable form, but then also expose that date in ISO 8601 format when talking to the server.
This is a perfect job for a custom knockout extender.
This fiddle shows such an extender, along with an example of it in use.
In this case, I decided to extend the date field itself with a computed observable called formattedDate which exposes a read/write human readable value for the date. The original date field itself is left alone to track the ISO date value. Writing to either will update the other. I’ve seen other examples that show adding the computed observable to the model itself, but I felt that it was cleaner to extend the actual field rather than have two fields on the model itself representing the same data in different ways.
Note that in producing this fiddle I grabbed a good bit of helper code from around the web (why re-invent the wheel):
- Date.toISOString: is an ECMAScript 5 method. Since not all browsers support this yet, I’ve included a tiny extension that will add this to the date object on those browsers (code taken from Mozilla).
For any of the functionality added by these parsing and formatting extensions, you can choose other scripts or libraries to handle those jobs.