Parsing Date-and-Times from JavaScript to C#

I have some JavaScript code that I'm trying to pass to my web service. My JavaScript code is supposed to send a date in UTC format. Locally, the time that I generated my code at was at 12:30:43 pm. When I executed my JavaScript code, the following date/time was generated:


That date/time was generated from this code:

var now = new Date();
var utcDate = new Date(

When I pass the date/time from JavaScript back to my web service, it is serialized as shown here:


That looks correct to me at this point. I then need to take that string and convert it to a date/time in C#. In an attempt to do that, I'm using the following C# code:

DateTime _value = DateTime.MinValue;
DateTime.TryParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out _value)

When that happens, I get the following date/time. 6/3/2012 12:30:43 PM

What am I doing wrong? I was expecting the date/time to be 6/3/2012 4:30:43 PM



The result you get is correct, but please check the Kind property of your DateTime. You'll notice it's not set to UTC but to Local.

You can use DateTimeStyles.AdjustToUniversal to generate a DateTime with Kind set to UTC.

DateTime dateTime;
    DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
    out dateTime);

See it working on ideone.


If you just want to serialize using (e.g. webAPI) I find JS toISOString very useful and compatible.

var d = new Date();
$toPut.dateTime = d.toISOString();

[Put("/setup/dateTime"), HttpPut]
public HttpResponseMessage SetDateTime([FromBody]DateTime dateTimeSettings )

That way you can keep your data structure and not deal with parsing.


You must pass date parameter to web service as UTC format and then use TryParse method to convert it to C# date object.

Try this:

var now = new Date(); //just like: 'Thu, 21 Mar 2013 12:44:40 GMT'
var utcNowString = now.toUTCString(); //pass this parameter to your web service

And this is C# code:

DateTime date;
DateTime.TryParse(jsDateString, out date); //parsed as: '21.03.2013 14:44:40' 

Hope this helps.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.