Shasapo Shasapo - 1 year ago 73
Javascript Question

C# Convert datetime to date javascript

I sent a date time from controller using this variable

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
: The output is

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 :

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

Answer Source

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'));