DateTime.ParseExact format string
Solution 1
Might I suggest that instead of passing something like: "Wed Oct 03 2012 08:00:00 GMT-0400 (Eastern Daylight Time)" in your query string, that instead you simply pass the timestamp of the date? E.g., new Date().getTime(). (Number of milliseconds since 1970 in UTC). Then, in C# you could just do:
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var dt = epoch.AddMilliseconds(Convert.ToInt64(Request.QueryString["start"]));
No parsing required.
Solution 2
It may just be that your format doesn't cover the (Eastern Daylight Time)
section. Try parsing that out of your string using regular string handling methods, then calling ParseExact
on the remainder.
Edit: As Oded points out, you'll also have to put the GMT
into your format string as a literal:
"ddd MMM dd yyyy HH:mm:ss 'GMT'zzz"
The following works:
var input = "Wed Oct 03 2012 08:00:00 GMT-0400 (Eastern Daylight Time)";
var trim = input.Substring(0, input.IndexOf(" ("));
var dt = DateTime.ParseExact(
trim,
"ddd MMM dd yyyy HH:mm:ss 'GMT'zzz",
CultureInfo.InvariantCulture);
Matt
Updated on June 04, 2022Comments
-
Matt almost 2 years
I have a web application that passes a DateTime from one page to another through the query string. It was working just fine in both IE and FireFox, but was throwing exceptions whenever I tried it in Google Chrome. The program is choking on the following line:
startDateTime = Convert.ToDateTime(Request.QueryString["start"]);
So, I ran the debugger and found that the value in the query string is:
Wed Oct 03 2012 08:00:00 GMT-0400 (Eastern Daylight Time)
I concluded that Convert just wasn't up to the job and set about trying to get DateTime.ParseExact to tame this beast. But, so far the correct format string has eluded me. Here's the code that I've been trying (which doesn't work):
DateTime.ParseExact(Request.QueryString["start"], "ddd MMM dd yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture);
This page is being called from another page through some JavaScript that is called by a third-party component (DayPilotCalendar). Here is the relevant property that is set on the DayPilotCalendar control:
TimeRangeSelectedJavaScript="GB_showPage('Request Magnet Time', '../../../EventAddEdit.aspx?start=' + encodeURIComponent(start) + '&end=' + encodeURIComponent(end))"
What is wrong with my format string?
-
Oded over 11 yearsThe
GMT
will give problems as well. -
Matt over 11 yearsSorry to reneg on the accept for your answer. Your code works, but I ended up going with the solution suggested by aquinas, as it seems that it is likely to be more robust.
-
Rawling over 11 yearsWell yes, if you've got control of what's generating the string, that makes much more sense...