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

前端 未结 7 1698
孤城傲影
孤城傲影 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:10

    No credit to me but this looks interesting for general DataTime parsing: http://www.codeproject.com/KB/datetime/date_time_parser_cs.aspx?msg=3299749

    0 讨论(0)
  • 2021-01-07 20:13

    What about strip them?

    string value = "Wednesday 13th January 2010";
    DateTime dt;
    DateTime.TryParseExact(
        Regex.Replace(value, @"(\w+ \d+)\w+ (\w+ \d+)", "$1 $2"),
        "ffffdd d MMMM yyyy", 
        DateTimeFormatInfo.InvariantInfo, 
        DateTimeStyles.None, out dt);
    
    0 讨论(0)
  • 2021-01-07 20:15

    Where does "th", "st","nd" or "rd" appear below?

    • monday
    • tuesday
    • wednesday
    • thursday
    • friday
    • saturday
    • sunday

    • january

    • february
    • march
    • april
    • may
    • june
    • july
    • august
    • september
    • october
    • november
    • december

    However you know those 4 will always be followed by a space. So unless I've missed something, a simple

    value = value.Replace("August","Augus").Replace("nd ","").Replace("st ","").Replace("nd ","").Replace("rd ","").Replace("Augus","August");
    DateTime dt;
    DateTime.TryParseExact(value,"DDDD dd MMMM yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt);
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-01-07 20:31

    Expanding on Kenny's approach, I added some code to pass integers to the DateTime variable...

    string sDate = "Wednesday 13th January 2010";
    string[] dateSplit = sDate.Split (' ');
    string day = dateSplit[1].Substring(0, dateSplit[1].Length - 2);
    int monthInDigit = DateTime.ParseExact(dateSplit[3], "MMMM", CultureInfo.InvariantCulture).Month;
    DateTime date = new DateTime(Convert.ToInt16(year), monthInDigit, day);
    
    0 讨论(0)
  • 2021-01-07 20:31

    Another approach.

    string sDate = "Wednesday 13th January 2010";
    string[] sFields = sDate.Split (' ');
    string day = sFields[1].Substring (0, (sFields[1].Length - 2));
    DateTime date = new DateTime (sFields[3], sFields[2], day);
    
    0 讨论(0)
提交回复
热议问题