A few weeks ago, Scott Hanselman blogged about the challenges with working with JSON dates and the ASP.NET Web API. In the post he described how the current version of the Web API sends back dates in Epoch time. The conclusion of his post was that JSON.NET, which the Web API will use OOTB, will use ISO 8601 for JSON dates moving forward.
A quick and easy way to do this with KnockoutJS is to use a “value converter” – this is just a specific type of computed observable that includes both a read and write function. In the jsFiddle below, the “read” function takes an epoch date and converts it to the yyyy-mm-dd format. I can edit the formatted date however I want and the “write” function will automatically be invoked to convert my formatted date back to epoch time. This completes to 2-way data binding:
Direct link to the jsFiddle.
This code does not take into account daylight savings time (there is also some manual string parsing for the dates) – however, there are other JS libraries you can incorporate into the code above that does take daylight savings time elegantly into account. As you can see, KnockoutJS provides some convenient features to transform between two different formats without having to litter your code with conditional logic all over the place.