Friday, March 23, 2018

Handle with JSON Dates in ASP.NET or ASP.NET MVC

Problem:
When we got date in the below format from the server when we are doing async call to get the data and it would be hard to read and format it again.
 "/Date(1521707071869)/"

Solution:
function toDate(dt) {
        var milisegundos = parseInt(dt.replace(/\/Date\((.*?)\)\//gi, "$1"));
        var newDate = new Date(milisegundos);

//return newDate.toLocaleString("en-US"), {weekday: "long", year: "numeric", month: "short",
//    day: "numeric", hour: "2-digit", minute: "2-digit"};
//Or
        return newDate.toLocaleDateString("en-US") + " " + newDate.toLocaleTimeString("en-US", { "second": "2-digit", "minute": "2-digit", "hour": "2-digit" });
    }