13

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!

4 Answers 4

25

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

var myJsDate = new Date();
var myDotNetDate = myJsDate.toISOString();
Sign up to request clarification or add additional context in comments.

1 Comment

perfect solution!
8

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

2 Comments

From .NET 4.6 use DateTimeOffset.FromUnixTimeMilliseconds(msec).DateTime
@AndriyTolstoy, simple, elegant and working solution, should be the accepted answer
2

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

Comments

2

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.