简体   繁体   English

为什么字符串不能转换为日期时间?

[英]Why string cannot be converted to dateTime?

I have this string:我有这个字符串:

 {2018-06-17 10:05:41}

At some point I try to convert it to DateTime:在某些时候,我尝试将其转换为 DateTime:

  DateTime.ParseExact(cell.StringCellValue, "dd/MM/yyyy", CultureInfo.InvariantCulture);

But I get this exception:但我得到这个例外:

 "String was not recognized as a valid DateTime."

Any idea why string above not recognized as a DateTime and how to fix it?知道为什么上面的字符串不被识别为 DateTime 以及如何修复它吗?

Because you are using the wrong format - 2018-06-17 10:05:41 is yyyy-MM-dd HH:mm:ss (not sure about the HH part, it might be hh , but the lack of AM/PM is a hint).因为您使用了错误的格式 - 2018-06-17 10:05:41yyyy-MM-dd HH:mm:ss (不确定HH部分,可能是hh ,但缺少AM/PM是一个提示)。

Also, you would be better off using TryParseExact then ParseExact :此外,您最好使用TryParseExact然后使用ParseExact

DateTime dateTime;
DateTime.TryParseExact(
    cell.StringCellValue, 
    "yyyy-MM-dd HH:mm:ss", 
    CultureInfo.InvariantCulture, 
    DateTimeStyles.None, 
    out dateTime);

since you will not have to handle exceptions in case the parse fails.因为万一解析失败,您将不必处理异常。

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

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