简体   繁体   中英

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.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?

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).

Also, you would be better off using TryParseExact then 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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