简体   繁体   English

将 JSON 日期时间 object 转换为 JavaScript ZA8CFDE6331BD59EB2AC96F8911C4B666

[英]Converting JSON datetime object to JavaScript object

My JSON returns the object as this我的 JSON 像这样返回 object

"/Date(1307514780000+0530)" 

How do I convert this to my JavaScript date time object?如何将此转换为我的 JavaScript 日期时间 object? Also, what does +0530 mean?另外, +0530是什么意思?

By “My JSON”, I surmise that you're referring to the way that Microsoft ASP.NET passes a date-time object not as you have written, but with a slash also at the end:通过“我的 JSON”,我推测您指的是 Microsoft ASP.NET 传递日期时间 object 的方式,而不是您所写的,但在末尾还有一个斜杠:

/Date(1307514780000+0530)/

JSON doesn't support the native JavaScript Date() type, so this is actually a simple JSON string, but Microsoft hacks at it a bit more and actually sends this: JSON 不支持本机 JavaScript Date()类型,所以这实际上是一个简单的 JSON 字符串,但微软在这方面做了一些修改:

\/Date(1307514780000+0530)\/

And that's allowed for a JSON string, even if the backslashes aren't necessary.这对于 JSON 字符串是允许的,即使反斜杠不是必需的。 (The two strings are identical to your JSON client software, but When Microsoft JScript sees these backslashes, it treats it as a special structure. And, yes, this is a supreme hack.) (这两个字符串与您的 JSON 客户端软件相同,但是当 Microsoft JScript 看到这些反斜杠时,它会将其视为特殊结构。而且,是的,这是一个至高无上的 hack。)

The value before the sign (which can also be “-”) is the number of milliseconds since 1970-01-01 00:00:00 UTC.符号前的值(也可以是“-”)是自 1970-01-01 00:00:00 UTC 以来的毫秒数。 The sign and the value after it represent the presentation time zone, which isn't necessary to convert the value to a native JavaScript Date() object.符号和它后面的值表示演示时区,不需要将值转换为本机 JavaScript Date() object。 The sign indicates if the time zone is before (+) or after (-) UTC and the numbers are formatted as “HHMM”, where “HH” is the number of hours and “MM” is the number of minutes.该符号表示时区是在 (+) 之前还是之后 (-) UTC,并且数字的格式为“HHMM”,其中“HH”是小时数,“MM”是分钟数。 (In this instance, “+0530” is the same time zone offset as India Standard Time, aka “IST”.) (在这种情况下,“+0530”是与印度标准时间相同的时区偏移,也就是“IST”。)

To convert it to a native Date() object using standard cross-browser-compatible JavaScript:使用标准的跨浏览器兼容的 JavaScript 将其转换为本机Date() object:

function getDateFromAspString(aspString) {
  var epochMilliseconds = aspString.replace(
      /^\/Date\(([0-9]+)([+-][0-9]{4})?\)\/$/,
      '$1');
  if (epochMilliseconds != aspString) {
      return new Date(parseInt(epochMilliseconds));
  }
}

Note that this function doesn't return anything if the string is not an ASP.NET date-time string.请注意,如果字符串不是 ASP.NET 日期时间字符串,则此 function 不会返回任何内容。 You can compare (===) the result to undefined to see if anything was returned.您可以将 (===) 结果与未定义进行比较,以查看是否返回了任何内容。

On my browser, this invocation:在我的浏览器上,这个调用:

getDateFromAspString("/Date(1307514780000+0530)/").toString()

returns this string:返回此字符串:

"Wed Jun 08 2011 01:33:00 GMT-0500 (Central Daylight Time)"

See also:也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM