3 rules
3 rules

Reputation: 1409

Convert Json date to "Date" in javascript

I am using Visual Studio 2013 with C#.

I am calling one ActionResult method that returns the list of data from Ajax.

The problem here is I am getting date as "/Date(1460008501597)/".

I don't know how to convert it to display on form using javascript.

Please someone help me it's hard for me to solve.

Upvotes: 2

Views: 8913

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386578

You could use a function which return a date if the date string is in the wanted form or the value itself.

function getDateIfDate(d) {
    var m = d.match(/\/Date\((\d+)\)\//);
    return m ? (new Date(+m[1])).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : d;
}

console.log(getDateIfDate("/Date(1460008501597)/"));
console.log(getDateIfDate('abc'));

Upvotes: 5

3 rules
3 rules

Reputation: 1409

I have done it like this:(Is it ok)

function getDateIfDate(d) {
        var m = d.match(/\/Date\((\d+)\)\//);
        return (new Date(+m[1])).getMonth() + "/" + (new Date(+m[1])).getDate() + "/" + (new Date(+m[1])).getFullYear();
        //return m ? (new Date(+m[1])) : d;
    }

Upvotes: 0

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

In pure javascript, you can do this:

var date = new Date(Number("/Date(1460008501597)/".replace(/\D/g, '')));

Explanation:

new Date(
    Number(
        "/Date(1460008501597)/".replace(/\D/g, '') // Removes all non digit characters
    ) // Cast it to numeric
) // Creates a new Date object with the resultant number

Now, for more accurate solution for your problem, like display the date w/o javascript(which I think would be better choice), you can improve your question with more detail/information/code.

Upvotes: 5

Related Questions