2017-06-21 149 views
2

我有不同的日期時間格式。當我嘗試解析它時,出現錯誤'System.FormatException' 。我怎麼解析它?如何從此格式解析日期時間?

?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)} 

由於偏移量是硬編碼或存在數據庫派生,因此沒有公佈的答案處理夏令時。

+0

[將字符串解析爲C#中的DateTime]可能的重複(https://stackoverflow.com/questions/5366285/parse-string-to-datetime-in-c-sharp) – lebelinoz

+0

[Parse DateTime with time形式爲PST/CEST/UTC/etc]的區域(https://stackoverflow.com/questions/241789/parse-datetime-with-time-zone-of-form-pst-cest-utc-etc) –

+0

其不是重複,因爲該鏈接沒有解決日光節省偏移 – junkone

回答

1

DateTime.Parse()方法無法識別當前日期時間字符串,所以你需要將它重新格式化爲的,這種方法可以理解的格式之一。 下面的代碼片段可能有點矯枉過正:-)這個問題,但它可以處理不少場景。

// "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); 
} 

希望這可以提供幫助。

3

EST是UTC落後5小時,用DateTime.ParseExact可能適合您的需要:

String time = "20170620 21:22:02 EST"; 

DateTime.ParseExact(time.Replace("EST", "-05:00"), "yyyyMMdd HH:mm:ss zzz", CultureInfo.InvariantCulture); 

結果在UTC:

6/21/2017 2:22:02 AM 

注:根據IANA's數據,有些時區的縮寫有不同的關聯取決於文化,因此沒有確切的方法來定義應該解析哪個時區,而不是在應用程序上下文中定義它們(可能使用硬編碼值)。

.NET Fiddle Example

+0

這個選項的問題是,由於日光節省,EST並不總是-05:00 – junkone

+0

對於這種情況下,您需要使用EDT(夏令時版本) 。如果您使用EST/EDT以外的其他時區,請先將它們指定到列表中。 –

+0

當你硬編碼的偏移量,然後它不正確的偏移量基於週期的變化。 https://www.timeanddate.com/time/zone/canada/toronto – junkone