2017-06-21 167 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