javascript / json日期文字 [英] javascript/json date literal

查看:111
本文介绍了javascript / json日期文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

日期文字被提出,然后收回,也许我们会在ECMA的未来版本中看到它们-262规格。



由于没有日期文字在JavaScript中,JSON没有字面意思(如果JavaScript引擎无法解析,则JavaScript对象符号不会太好)。诚然,这是不幸的。许多网络服务将输出 ISO 8601 字符串,例如 2010-03-23T23:57Z ,但是为了在JavaScript中解析,您需要使用自定义库,创建自定义函数或依赖于ECMAScript 5的Date解析规范,其中指出实现应本地解析ISO 8601字符串。



如果是您自己的JSON,将在JavaScript中解析,您可以使用一些简单的例如从1970年1月1日00:00以来的毫秒,使用标识符,然后传递一个reviver函数JSON.parse:

  var myJSON ='{MyDate:@ 1269388885866 @}'
var myObj = JSON.parse(myJSON,function(key,value)
{
//编辑:不要忘记检查type == string!
if(typeof value == string&& value.slice(0,1)==@&&  value.slice(-1)==@)
返回新日期(+ value.substring( 1,-1));
else
返回值;
}

显然,您需要使用现代浏览器中的本机JSON对象或 json2.js 在解析时使用reviver。


What's the date literal for JSON/JavaScript ( if such thing does exists? )

解决方案

Date literals were proposed and then retracted, maybe we'll see them in a future edition of the ECMA-262 specification.

Since there is no Date literal in JavaScript, there is no literal for JSON either (JavaScript Object Notation wouldn't be too good a name if it couldn't be parsed by a JavaScript engine ;-)). Admittedly, this is unfortunate. Many web services will output an ISO 8601 string, e.g. 2010-03-23T23:57Z, but in order to parse it in JavaScript you would need to use a custom library, create a custom function or rely on ECMAScript 5th's Date parsing specification, which states that implementations should parse ISO 8601 strings natively.

If it's your own JSON that's going to be parsed in JavaScript, you could use something simple like milliseconds since January 1st 1970 00:00 with an identifier and then pass a reviver function to JSON.parse:

var myJSON = '{"MyDate":"@1269388885866@"}'
var myObj  = JSON.parse(myJSON, function (key, value)
{
   // Edit: don't forget to check the type == string!
   if (typeof value == "string" && value.slice(0, 1) == "@" && value.slice(-1) == "@")
       return new Date(+value.substring(1, -1));
   else
       return value;
}

Obviously, you'd need to use the native JSON object found in modern browsers or json2.js to use the reviver when parsing.

这篇关于javascript / json日期文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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