Search code examples
javascriptasp.netdatetimeepoch

Invoking javascript time "object"


A webservice of mine returns an object in the following format.

{"UserID":"338040a3-6587-42bf-b22e-dc88f4ea3a9c","CompanyID":"823946a4-29d0-4546-a7ca-790648cf1e1a","FirstName":"Maxim","LastName":"Gershkovich","Username":"MaximG","Password":"62198e58d57843967bc34824be77ee2f1e2abcbbe389dc41c06810ed6f9561bf","Email":"[email protected]","SignupDate":"/Date(1272631625210)/","IsAdmin":true,"LoginTime":"/Date(1297129238517)/"}"

What is the optimal way to take the datetime value it returns and convert it to a javascript date object?

"SignupDate":"/Date(1272631625210)/"

The only way I can think of is to strip the first and last char and then do an eval. Is there a better way?


Solution

  • You can do it with regex and Date constructor.

    Not sure if it better, but it is safer. Eval can be evil sometimes...

    So, you could do something like this:

    var millisecs = signupDate.match(/\d+/)[0];
    var date = new Date(parseInt(millisecs));
    

    You could also do the regex with replace:

    var millisecs = signupDate.replace(/[^\d]/g,""));