我最近开始使用KnockoutJs,并很快意识到使用默认的Json(myModelWithADate)
会产生默认的json编码\/Date(-62135578800000)\/
.通过一些研究,我找到了四种可能的方法来处理dom元素中日期的显示.
1) Create a binding that handles the conversion from the Json date to the format you desire
ko.bindingHandlers.date = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var jsonDate = valueAccessor();
var value = new Date(parseInt(jsonDate.substr(6)));
var ret = value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear();
element.innerHTML = ret;
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
}
};
用法
<td data-bind="date: DueDate">
</td>
2) Return “strings” from your Controller
return Json(new {MyDate = DateTime.Now.ToShortDateString()});
3) Use the JSON.NET to specify a Date Time format seen over at 100
示例
string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
// {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}
4) use JSON.parse to handle your dates as seen in this 100
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;
});
它们似乎都很管用,但我仍在为哪一种感觉"正确"而苦苦挣扎.现在,我的直觉是混合使用绑定和返回字符串.正如我可以看到的那样,我自己扩展了绑定以使用jQuery UI Datepicker控件处理输入.
Is there an accepted practice when handling displaying dates or other types such as currency? Is there another option I am missing that solves this problem?