2

我有一个包含日期时间的字符串...

string S="08/18/2013 24:00:00"
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy HH:mm:ss", null);

我想将其解析为日期时间,但显示这样的异常。日历 System.Globalization.GregorianCalendar 不支持字符串表示的 DateTime。

请告诉我这个问题的任何解决方案。

4

3 回答 3

10

问题在于 24 小时DateTime。据我所知,不支持这一点。

选项:

  • 使用我的Noda Time项目,它确实支持 24:00:00,但基本上通过添加一天来处理它(它不会保留那个和“前一天结束”之间的区别)
  • 继续使用DateTime,发生时手动将“24:00:00”替换为“00:00:00”,之后记得加一天

如果您想保留实际上是“一天结束”的信息,您需要单独执行此操作,并将信息保留在DateTime/旁边LocalDateTime

正如其他答案所建议的那样,您还应该使用不变的文化进行解析-您不是在尝试解析特定于文化的字符串;你知道确切的分隔符等。

于 2013-07-25T11:39:12.483 回答
1
string S="08/18/2013 00:00:00";  // here is the first problem occurred
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
于 2013-07-25T11:38:05.013 回答
0

The "HH" Custom Format Specifier

The "HH" custom format specifier (plus any number of additional "H" specifiers) represents the hour as a number from 00 through 23; that is, the hour is represented by a zero-based 24-hour clock that counts the hours since midnight.

So, using 24 as an hour is invalid on this case.

Try with hh format with 00 instead like;

string S = "08/18/2013 00:00:00";
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);

Here a DEMO.

If you really want to use 24:00:00 as a hour, take a look Noda Time which developed by Jon.

于 2013-07-25T11:39:32.060 回答