4

I'm getting dates back from a webservice, and they look like this:

/Date(1310187160270+1200)/

How would I go about converting this to a date object in javascript?

I've googled around a bit and cannot find a decent answer - this may be in part due to the fact that I'm not exactly sure what this type of date object is called - so if someone could shed light on that also, that would be appreciated.

ahren
  • 16,443
  • 5
  • 49
  • 70

2 Answers2

7
var date = new Date(1310187160270+1200); 
console.log(date)

returns

Sat Jul 09 2011 06:52:41 GMT+0200 (South Africa Standard Time)

If you need to strip it as is in Question:

var returnVariable = "/Date(1346713200000+0100)/";
var d = new Date(parseFloat(returnVariable.replace("/Date(", "").replace(")/", ""))); 
SpYk3HH
  • 21,961
  • 10
  • 67
  • 81
BlackSpy
  • 5,428
  • 4
  • 27
  • 37
5

As the previous answer does not handle timezone offsets, I'll throw in my version:

function fromDateString(str) {
    var res = str.match(/\/Date\((\d+)(?:([+-])(\d\d)(\d\d))?\)\//);
    if (res == null)
        return new Date(NaN); // or something that indicates it was not a DateString
    var time = parseInt(res[1], 10);
    if (res[2] && res[3] && res[4]) {
        var dir = res[2] == "+" ? -1 : 1,
            h = parseInt(res[3], 10),
            m = parseInt(res[4], 10);
        time += dir * (h*60+m) * 60000;
    }
    return new Date(time);
}

Correct result is Fri Jul 08 2011 18:52:40 GMT+0200, or Fri, 08 Jul 2011 16:52:40 GMT.

Bergi
  • 572,313
  • 128
  • 898
  • 1,281