如何将JSON DateTime转换为可读的Date&时间使用Knockout和自定义绑定 [英] How to convert JSON DateTime into readable Date & time using Knockout and custom bindings

查看:434
本文介绍了如何将JSON DateTime转换为可读的Date&时间使用Knockout和自定义绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用KnockoutJS与映射插件,除了DateTime字段,它被序列化为如下所示的ticks:/ Date(x)/ where x = ticks。

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.

我如何:
1)将日期对象解析为人类可读的形式?
2)将自定义绑定返回模型中的值?

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?

推荐答案

我不知道关于KnockoutJS的任何事情,所以可能会有一个更好的方法来做这个已经内置。我也不知道第二个问题。希望一个真正了解它的人可以帮助你。

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.

所以,使用这个免责声明,您可以使用简单JavaScript转换它(您可能需要包括Douglas Crockford的 json2.js 如果您想支持旧浏览器)。 JSON.parse 采用可选的 reviver 参数,可以在解析时替换每个值。

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;
});

这篇关于如何将JSON DateTime转换为可读的Date&时间使用Knockout和自定义绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆