Parsing a Date with Month name to C# DateTime

前端 未结 2 1022
抹茶落季
抹茶落季 2020-12-18 01:56

I want to parse the following date format to a DateTime object in C#.

\"19 Aug 2010 17:48:35 GMT+00:00\"

How can I accomplish this?

相关标签:
2条回答
  • 2020-12-18 02:26

    I'd recommend using DateTime.ParseExact.

    DateTime.ParseExact(dateString, "dd MMM yyyy H:mm:ss \\G\\M\\Tzzz", System.Globalization.CultureInfo.InvariantCulture);
    

    As suggested in the comments below, System.Globalization.CultureInfo.CurrentCulture is a good thing to be aware of and use if you are doing a desktop application.

    0 讨论(0)
  • 2020-12-18 02:36

    I know my answer is a bit out of scope, but it might be helpful anyway. My problem was a bit different, I had to extract the highest date of a string, that might be in various formats (1.1.98, 21.01.98, 21.1.1998, 21.01.1998). These are two static methods that can be added to any class:

    public static DateTime ParseDate(string value)
    {
        DateTime date = new DateTime();
        if (value.Length <= 7) // 1.1.98, 21.3.98, 1.12.98, 
            DateTime.TryParseExact(value, "d.M.yy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeLocal, out date);
        else if (value.Length == 8 && value[5] == '.') // 21.01.98
            DateTime.TryParseExact(value, "dd.MM.yy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeLocal, out date);
        else if (value.Length <= 9) // 1.1.1998, 21.1.1998, 1.12.1998
            DateTime.TryParseExact(value, "d.M.yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeLocal, out date);
        else if (value.Length == 10) // 21.01.1998
            DateTime.TryParseExact(value, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeLocal, out date);
        return date;
    }
    
    public static DateTime? ExtractDate(string text)
    {
        DateTime? ret = null;
        Regex regex = new Regex(@"\d{1,2}\.\d{1,2}\.\d{2,4}");
        MatchCollection matches = regex.Matches(text);
        foreach (Match match in matches)
        {
            DateTime date = ParseDate(match.Value);
            if (ret == null || ret < date)
                ret = date;
        }
        return ret;
    }
    
    0 讨论(0)
提交回复
热议问题