Parsing a DateTimeOffset string in C#

血红的双手。 提交于 2019-12-11 13:40:08

问题


I need parse datetimeoffsets from strings of multiple formats. One of the strings that fail is: 08/12/1992 07.00.00 -05:00

Now when I try to parse this, I use:

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

Which gives a FormatException:

"String was not recognized as a valid DateTime."

I can also try to add delimiters in the separators:

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

...or other permutations of small/capital letter or separators, but I get the same error.

Can anyone tell me why the ParseExact lines above do not work, and how to correct them?

EDIT: I tried using a LINQ query to replace the colon with dots (: -> .). Apparently that did not work correctly - thanks for the replies.


回答1:


Your actual date (actually time) string delimits the hours from the minutes from the seconds with a dot ., so your format must do the same:

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

If you have multiple string formats in your data, you can do something like this:

    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;
    }



回答2:


In the statement

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

the format string uses : as separator for the time parts, but the data argument uses . as separator.



来源:https://stackoverflow.com/questions/32824186/parsing-a-datetimeoffset-string-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!