[英]Parsing a Date with Month name to C# DateTime
I want to parse the following date format to a DateTime object in C#.我想将以下日期格式解析为 C# 中的 DateTime 对象。
"19 Aug 2010 17:48:35 GMT+00:00"
How can I accomplish this?我怎样才能做到这一点?
I'd recommend using DateTime.ParseExact
.我建议使用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.正如下面的评论中所建议的那样,如果您正在开发桌面应用程序, System.Globalization.CultureInfo.CurrentCulture
是一个需要注意和使用的好东西。
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).我的问题有点不同,我必须提取字符串的最高日期,这可能是各种格式(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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.