且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

DateTime.TryParse无法分析DateTime.MinValue

更新时间:2023-11-29 14:00:04

为什么要用DateTimeStyles.RoundtripKind?该文档RoundtripKind说:

Why use DateTimeStyles.RoundtripKind? The documentation for RoundtripKind says:

日期的DateTimeKind场是当一个DateTime对象转换为使用O或R的标准格式说明符的字符串,字符串,然后转换回一个DateTime对象preserved。

The DateTimeKind field of a date is preserved when a DateTime object is converted to a string using the "o" or "r" standard format specifier, and the string is then converted back to a DateTime object.

从O或R的标准格式说明输出的字符串是不喜欢的ISO 8601字符串你正在试图解析。这听起来并不对我来说,RoundtripKind真的应该与任何日期时间字符串格式工作。这听起来像往返对于DateTime.Kind属性时,该字符串是在一个特定的格式。

The string output from the "o" or "r" standard format specifiers are not like the ISO 8601 string you are trying to parse. It doesn't sound to me like RoundtripKind is really supposed to work with any date time string format. It sounds like the round trip is for the DateTime.Kind property when the string is in a particular format.

既然你知道你正试图解析字符串的格式,那么我会建议使用DateTime.TryParseExact。

Since you know the format of the string you are trying to parse, then I would suggest using DateTime.TryParseExact.

我不得不支持了几个不同版本的ISO 8601字符串 - 无论这些格式都是有效的日期时间值在ISO 8601(也有日期,时间和分数秒甚至更多的选择,但我没有'牛逼的):

I have had to support a couple different versions of the ISO 8601 string - either of these formats are valid date-time values in ISO 8601 (and there are even more options for dates, times and fractional seconds, but I didn't those):

0001-01-01T00:00:00 + 00:00

0001-01-01T00:00:00+00:00

0001-01-01T00:00:00Z

0001-01-01T00:00:00Z

下面是将要处理或者这些格式的方法:

Here's a method that will handle either of these formats:

private bool TryParseIso8601(string s, out DateTime result)
{
    if (!string.IsNullOrEmpty(s))
    {
        string format = s.EndsWith("Z") ? "yyyy-MM-ddTHH:mm:ssZ" : "yyyy-MM-ddTHH:mm:sszzz";
        return DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out result);
    }

    result = new DateTime(0L, DateTimeKind.Utc);
    return false;
}