简体   繁体   English

如何将任何格式的字符串转换为 DateTime

[英]How to convert string with any format To DateTime

I have a DateTime as string with different formats in Excel.我在 Excel 中有一个DateTime作为具有不同格式string I want to convert the string format to DateTime using c#.我想使用 c#string格式转换为DateTime but I am getting the following exception:但我收到以下异常:

string was not recognized as valid date time.字符串未被识别为有效日期时间。

DateTimeOffset.Parse("09/20/2019 17:25:59");

Expected:预期的:

09/20/2019 17:25:59 2019 年 9 月 20 日 17:25:59

Actual:实际的:

System.FormatException System.FormatException

You can use DateTime.ParseExact Doc here您可以在这里使用DateTime.ParseExact Doc

var dateThatDesired = DateTime.ParseExact("09/20/2019 17:25:59","MM/dd/yyyy HH:mm:ss",CultureInfo.InvariantCulture);

If you have limited numbers of formats in the excel table you can test them with DateTime.TryParseExact() and if return with a success you can use the parsed dateTime which you will get with out parameter.如果您在 excel 表中的格式数量有限,您可以使用DateTime.TryParseExact()对其进行测试,如果返回成功,您可以使用已解析的 dateTime,您将使用out参数获得。

First of all, there is no universal format , since date representations are ambiguous , a classical example is首先,没有通用格式,因为日期表示是模棱两可的,一个经典的例子是

 01/02/03 == 2 Jan 2003 (USA)  
 01/02/03 == 1 Feb 2003 (Russia) 
 01/02/03 == 3 Feb 2001 (China) 

If you have a collection of expected formats, you can try ParseExact , eg如果您有一系列预期格式,您可以尝试ParseExact ,例如

 string[] possibleFormats = new[] {
   "MM'/'dd'/'yyyy HH:mm:ss",   // USA
   "dd'.'MM'.'yyyy HH:mm:ss",   // Russia
   "yyyy'-'MM'-'dd HH:mm:ss",   // China
   "yyyy'-'MM'-'dd'T'HH:mm:ss", // ISO 8601
 };

 string value = @"09/20/2019 17:25:59";

 DateTimeOffset result = DateTimeOffset.ParseExact(
   value, 
   possibleFormats, 
   CultureInfo.InvariantCulture, 
   DateTimeStyles.AssumeLocal);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM