DateTime ParseExact string was not recognize as a

2019-03-07 03:40发布

I'm trying to parse string as DateTime but I'm getting an error. here my code

return DateTime.ParseExact("01/01/0001 12:00:00 AM", "dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);

The date and its format is got from DataBase as string and I'm trying to add it to a DataColumn DateTime data type.

What's the problem?

Thanks.

2条回答
贼婆χ
2楼-- · 2019-03-07 03:58

You're using ParseExact, meaning you're specifying the whole format of the date and time - and the format specified is "dd/MM/yyyy", which covers "01/01/0001" but what does the poor function do with " 12:00:00 AM"? Look at http://msdn.microsoft.com/en-us/library/8kb3ffffd4.aspx.

Also, it's almost always better to use the "Try" functions for parsing - in this case "TryParseExact"

查看更多
劳资没心,怎么记你
3楼-- · 2019-03-07 04:08

You are trying to parse the DateTime exactly, therefore the format has to be exact

DateTime.ParseExact("01/01/0001 12:00:00 AM", "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
查看更多
登录 后发表回答