在 C# 中解析 DateTimeOffset 字符串

Parsing a DateTimeOffset string in C#

我需要从多种格式的字符串中解析日期时间偏移量。失败的字符串之一是: 1992 年 8 月 12 日 07.00.00 -05:00

现在,当我尝试解析它时,我使用:

DateTimeOffset.ParseExact("08/12/1992 07.00.00 -05:00", "dd/MM/yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture)

这给出了 FormatException

"String was not recognized as a valid DateTime."

我也可以尝试在分隔符中添加分隔符:

DateTimeOffset.ParseExact("08/12/1992 07.00.00 -05:00", "dd'/'MM'/'yyyy HH':'mm':'ss zzz", CultureInfo.InvariantCulture)

...或 small/capital 字母或分隔符的其他排列,但我得到相同的错误。

谁能告诉我为什么上面的 ParseExact 行不起作用,以及如何更正它们?

编辑: 我尝试使用 LINQ 查询将冒号替换为点 (: -> .)。显然那没有正常工作 - 感谢您的回复。

您的实际日期(实际时间)字符串用点 . 分隔小时与分钟与秒,因此您的格式也必须如此:

DateTimeOffset.ParseExact("08/12/1992 07.00.00 -05:00", 
    "dd/MM/yyyy HH.mm.ss zzz", CultureInfo.InvariantCulture)
//                ^  ^
//                |  |

如果您的数据中有多种字符串格式,您可以这样做:

    public static DateTimeOffset Parse(string str)
    {
        string[] formats =
        {
            "dd/MM/yyyy HH.mm.ss zzz",
            "dd/MM/yyyy HH:mm:ss zzz"
            // ... possibly more ...
        };

        var dto = new DateTimeOffset();
        if (!formats.Any(f => DateTimeOffset.TryParseExact(str, f, CultureInfo.InvariantCulture, DateTimeStyles.None, out dto)))
        {
            throw new ArgumentException("Unrecognized date format");
        }

        return dto;
    }

在声明中

DateTimeOffset.ParseExact("08/12/1992 07.00.00 -05:00",
                          "dd/MM/yyyy HH:mm:ss zzz",
                          CultureInfo.InvariantCulture)

格式字符串使用 : 作为时间部分的分隔符,但数据参数使用 . 作为分隔符。