Reputation: 1465
i have a different format of datetime. I get errors 'System.FormatException' when I try to parse it. how can I parse it?
?time
"20170620 21:22:02 EST"
?DateTime.Parse(time)
'DateTime.Parse(time)' threw an exception of type 'System.FormatException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233033
HelpLink: null
InnerException: null
Message: "String was not recognized as a valid DateTime."
Source: "mscorlib"
StackTrace: " at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)\r\n at System.DateTime.Parse(String s)"
TargetSite: {System.DateTime Parse(System.String, System.Globalization.DateTimeFormatInfo, System.Globalization.DateTimeStyles)}
None of the answers posted deal with daylight savings as the offset is hardcoded or there is a database derivation.
Upvotes: 2
Views: 1897
Reputation: 384
DateTime.Parse() method doesn't recognize your current date time string, so you need to reformat it into one of the formats that this method can understand. The following snippet could be a bit overkill :-) for this problem but it can handle quite a few scenarios.
// "20170620 21:22:02 EST" -> "wrong" format
// "2017-06-20T21:22:02 -05:00" -> correct format
String input = "20170620 21:22:02 EST";
String temp = input;
// Handle US time zones.
String[] timeZones = {"AST", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT", "AKST", "AKDT", "HST", "HAST", "HADT", "SST", "SDT", "CHST"};
Int32[] utcOffsets = { -4, -5, -4, -6, -5, -7, -6, -8, -7, -9, -8, -10, -10, -9, -11, -10, 10 };
// Correct the timezone part
for (int i = 0; i < timeZones.Length; i++)
{
String timeZonePattern = @"\b" + timeZones[i] + @"\b";
String timeZoneReplPattern = String.Format("{0}:00", utcOffsets[i].ToString("+00;-00"));
temp = Regex.Replace(input, timeZonePattern, timeZoneReplPattern);
if (temp != input)
{
break;
}
}
// Correct the date part
String datePattern = @"(?<year>[\d]{4})(?<month>[0][1-9]|[1][0-2])(?<day>[0][1-9]|[1-2][0-9]|3[0-1])\s*";
String dateReplPattern = @"${year}-${month}-${day}T";
temp = Regex.Replace(temp, datePattern, dateReplPattern);
// Now we should have a correct date time string
DateTime dt;
try
{
dt = DateTime.Parse(temp);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Hope this can help.
Upvotes: 1
Reputation: 24957
EST is 5 hours behind the UTC, so using DateTime.ParseExact
may fit on your need:
String time = "20170620 21:22:02 EST";
DateTime.ParseExact(time.Replace("EST", "-05:00"), "yyyyMMdd HH:mm:ss zzz", CultureInfo.InvariantCulture);
Result in UTC:
6/21/2017 2:22:02 AM
NB: Depending on IANA's data, some timezone abbreviations have different associations depending on culture, hence there is no exact method to define which timezone should be parsed instead of defining them in application context (possibly using hardcoded values).
Upvotes: 3