Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JavaScript Date to .NET DateTime

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!

like image 944
Christian Agius Avatar asked May 22 '12 10:05

Christian Agius


4 Answers

The following parses well with the default DateTime modelbinder in a .NET MVC Controller:

var myJsDate = new Date();
var myDotNetDate = myJsDate.toISOString();
like image 76
Martin Åhlin Avatar answered Oct 23 '22 21:10

Martin Åhlin


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
like image 43
Jon Avatar answered Oct 23 '22 22:10

Jon


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);
like image 2
The BitMaster Avatar answered Oct 23 '22 22:10

The BitMaster


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;
like image 2
Marco Lackovic Avatar answered Oct 23 '22 21:10

Marco Lackovic