Convert JavaScript Date to .NET DateTime

16,771

Solution 1

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

Solution 2

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

var myJsDate = new Date();
var myDotNetDate = myJsDate.toISOString();

Solution 3

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

Solution 4

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;
Share:
16,771
Christian Agius
Author by

Christian Agius

Updated on June 12, 2022

Comments

  • Christian Agius
    Christian Agius about 2 years

    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!

  • Andriy Tolstoy
    Andriy Tolstoy over 6 years
    From .NET 4.6 use DateTimeOffset.FromUnixTimeMilliseconds(msec).DateTime
  • user2145393
    user2145393 over 4 years
    perfect solution!
  • Nelson Garcia
    Nelson Garcia over 2 years
    @AndriyTolstoy, simple, elegant and working solution, should be the accepted answer