开发者

Parsing a Date with Month name to C# DateTime

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

开发者_StackOverflow中文版
"19 Aug 2010 17:48:35 GMT+00:00"

How can I accomplish this?


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜