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 w
Solution 1:
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;
DateTime.TryParseExact(
value,
"yyyyMMddHHmmss",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
out dateTime);
See it working on ideone.
Solution 2:
If you just want to serialize using (e.g. webAPI) I find JS toISOString
very useful and compatible.
//JAVASCRIPT
var d = new Date();
$toPut.dateTime = d.toISOString();
$toPut.put()
//C#
[Put("/setup/dateTime"), HttpPut]
public HttpResponseMessage SetDateTime([FromBody]DateTime dateTimeSettings )
That way you can keep your data structure and not deal with parsing.
Solution 3:
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:
//Javascript
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.
Post a Comment for "Parsing Date-and-Times From JavaScript To C#"