1

我正在尝试使这条线工作:

MyDateTime = DateTime.ParseExact("2/8/2013 11:59:00 AM", "yyyy-mm-dd hh:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo)

date/time从上述格式的电子表格中获取字符串,但我无法控制它。网上有很多关于将字符串转换为日期的帮助,包括这个网站,我都试过了,但我一直收到这个错误:

"System.FormatException: String was not recognized as a valid DateTime."

我正准备编写自己的自定义解析器,但这似乎不太优雅。有没有一些内置的方法可以将像我这样的字符串转换为date/time我需要的格式?

谢谢你的帮助。

4

2 回答 2

1

您的格式字符串错误。您正在输入d/M/yyyy hh:mm:ss tt格式的日期,但告诉它期望yyyy-mm-dd hh:mm:ss格式的日期。两者不完全匹配,因此DateTime.ParseExact非常正确地向您抛出异常。

尝试:

MyDateTime = DateTime.ParseExact("2/8/2013 11:59:00 AM", "d/M/yyyy hh:mm:ss tt", System.Globalization.DateTimeFormatInfo.InvariantInfo)

这告诉它期待以下字符:

Integer from 1 through 31 (depending on the length of the month)
/ character
Integer from 1 through 12
/ character
4 digit year
Space
Integer from 1 through 12
: character
Integer from 00 through 59
: character
Integer from 00 through 59
Space
Two character meridian specifier ("AM" or "PM")

有关日期时间格式字符串的更多信息,请查看此 MSDN 页面

于 2013-08-21T01:20:57.273 回答
0

我认为您需要更改字符串格式以匹配您传入的内容。您似乎传入的内容更像这样:

"d/M/yyyy hh:mm:ss"

试一试,看看它是如何工作的。请注意,您需要使用MM几个月——'mm' 用于几分钟。

于 2013-08-21T01:20:43.297 回答