Parsing a Date Like “Wednesday 13th January 2010” with .NET

前端 未结 7 1697
孤城傲影
孤城傲影 2021-01-07 19:49

How can I convert the following strings to a System.DateTime object?

Wednesday 13th January 2010
Thursday 21st January 2010
Wednesday 3rd February 2010

7条回答
  •  伪装坚强ぢ
    2021-01-07 20:20

    Another alternative using escape characters for handling (st, nd, rd, and th) without stripping them before the call of DateTime.TryParseExact

    string dtstr = "Saturday 23rd January 2016";
    DateTime dt;
    string[] formats = new string[] { 
        "ffffdd d\\s\\t MMMM yyyy", "ffffdd d\\n\\d MMMM yyyy",
        "ffffdd d\\r\\d MMMM yyyy", "ffffdd d\\t\\h MMMM yyyy" };
    bool result = DateTime.TryParseExact(dtstr, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
    

提交回复
热议问题