How to convert a C# DateTime object to a JavaScript Date object

When you are working with JSON and C# with DateTime objects, the serialized string of it looks like this:


In order to turn this into a usable JavaScript Date object you will need to strip out the non-numerical characters:

var cSharpDate = /Date(1425408717000)/ var stripedCsharpDate = cSharpDate.replace(/[^0-9 +]/g, '');

Note: some C# DateTime objects contain the time zone as well with the format looking like this:


So to retain the time zone information the regex does not strip the '+' chracter.

So now that we have the date that looks like this:


We turn it into a number and pass it to the JavaScript Date object.

`var stripedCSharpDateInt = parseInt(stripedCsharpDate); var jsDate = new Date(stripedCSharpDateInt);'

Now to summarize what I did below into two lines:

var cSharpDate = /Date(1425408717000)/ var jsDate = new Date(parseInt(cSharpDate.replace(/[^0-9 +]/g, '')));

Update: Typo in code fixed. Thanks Will!

Show Comments