简体   繁体   中英

Converting JSON datetime object to JavaScript object

My JSON returns the object as this

"/Date(1307514780000+0530)" 

How do I convert this to my JavaScript date time object? Also, what does +0530 mean?

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:

/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:

\/Date(1307514780000+0530)\/

And that's allowed for a JSON string, even if the backslashes aren't necessary. (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.)

The value before the sign (which can also be “-”) is the number of milliseconds since 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. 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. (In this instance, “+0530” is the same time zone offset as India Standard Time, aka “IST”.)

To convert it to a native Date() object using standard cross-browser-compatible JavaScript:

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. 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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