Shasapo Shasapo - 3 months ago 20
Javascript Question

C# Convert datetime to date javascript

I sent a date time from controller using this variable

IncidentReportedDt
the value is :
2016-08-11 09:30:30.287
to .cshtml and i want to display it by javascript.

if i just manually print this variable
IncidentReportedDt
: The output is
/Date(1470882630287)/


then i try some of the following tips :

var date3 = IncidentReportedDt.toDate();
var date4 = IncidentReportedDt.ToString();


it gives me this output :

TypeError: IncidentReportedDt.toDate is not a function
TypeError: IncidentReportedDt.toString is not a function


i tried another way using this :

var date = new Date(Date.parse(IncidentReportedDt));


and it's give me an output :
Invalid Date


so i add this code :

var date = new Date(Date.parse(IncidentReportedDt));
var dte = date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + (date.getUTCDate());


and it's give me an output :
NaN/NaN/NaN


i want the output :
2016-08-11 09:30
.
can you help me what's wrong with my code ?

Answer

I usually use the following function to convert this date format to JS format:

function parseDotNetDate(str) {
    var regexp = /\/Date\((\d*)\)\//;
    if (!regexp.test(str)) 
        throw new Error('Not a .NET DateTime object.');

    return new Date(+str.replace(regexp, '$1'));
}