Convert JavaScript Date to .NET DateTime

I get the Date value from JavaScript to the controller in MVC, and I would like to parse it in the .NET DateTime format, but it gave me an error, for example:

The string was not recognized as a valid DateTime.

JavaScript date format:

"Wed May 23 2012 01:40:00 GMT+0200 (W. Europe Daylight Time)" 

I tried this but did not work:

 DateTime.ParseExact(begin.Substring(1, 24), "ddd MMM d yyyy HH:mm:ss", CultureInfo.InvariantCulture); 

Can anyone give me some sample code please? thanks!

+7
source share
4 answers

Instead of parsing the text view, it would be more appropriate to construct a DateTime from a timestamp. To get the timestamp from JS Date :

 var msec = date.getTime(); 

And to convert msec (which is milliseconds) to DateTime :

 var date = new DateTime(1970, 1, 1, 0, 0, 0, 0); // epoch start date = date.AddMilliseconds(msec); // you have to get this from JS of course 
+6
source

The following parsing is well connected with the default DateTime modeling module in the .NET MVC controller:

 var myJsDate = new Date(); var myDotNetDate = myJsDate.toISOString(); 
+5
source

Here is what I did and why. Hope this helps.

JS Date var d = new Date()

returns: thu november 19 08:30:18 PST 2015

C # doesn't like this format, so convert it to UTC:

 var dc = d.toUTCString() 

returns: Thu, November 19, 2015 16:30:18 UTC

UTC - The worlds time standard is not a time zone, so you need to change it to a time zone

 var cr = dc.replace("UTC","GMT") 

now he is ready for

Thu, November 19, 2015 16:30:18 GMT

In one line

 var ol = d.toUTCString().replace("UTC","GMT")` 

Thu, November 19, 2015 16:30:18 GMT

for c #

 DateTime DateCreated= DateTime.Parse(ol); 
+1
source

You don't need to convert: By default, the Datebject ModelManager in the .NET MVC Controller works fine with the JavaScript Date object.

Using Moment.js

1) .NET DateTime -> JavaScript Date

 var jsDate = moment(dotNetDateTime).toDate(); 

2) JavaScript Date -> .NET DateTime

 var dotNetDateTime = jsDate; 
+1
source

All Articles