I getting a Date value from JavaScript to a controller in MVC and I would like to parse it to .NET format DateTime but its giving me an error such as:
The string was not recognized as a valid DateTime.
The Format of the JavaScript date is:
"Wed May 23 2012 01:40:00 GMT+0200 (W. Europe Daylight Time)"
I've tried this but its not working:
DateTime.ParseExact(begin.Substring(1, 24), "ddd MMM d yyyy HH:mm:ss", CultureInfo.InvariantCulture);
anyone can give me a sample code please? thanks!
The following parses well with the default DateTime modelbinder in a .NET MVC Controller:
var myJsDate = new Date();
var myDotNetDate = myJsDate.toISOString();
Instead of parsing a textual representation it would be more robust to construct a DateTime
from a timestamp instead. To get a timestamp from a JS Date
:
var msec = date.getTime();
And to convert msec
(which represents a quantity of milliseconds) into a 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
Here is what I did and why. I hope this Helps.
JS Date var d = new Date()
returns: Thu Nov 19 08:30:18 PST 2015
C# does not like this format so convert it to UTC:
var dc = d.toUTCString()
returns: Thu, 19 Nov 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 it is ready to
Thu, 19 Nov 2015 16:30:18 GMT
In one line
var ol = d.toUTCString().replace("UTC","GMT")`
Thu, 19 Nov 2015 16:30:18 GMT
for C#
DateTime DateCreated= DateTime.Parse(ol);
You don't need any conversion: the default DateTime modelbinder in a .NET MVC Controller works fine with a JavaScript Date object.
Using Moment.js
1) .NET DateTime -> JavaScript Date
var jsDate = moment(dotNetDateTime).toDate();
2) JavaScript Date -> .NET DateTime
var dotNetDateTime = jsDate;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With