我正在尝试聚合几个RSS源,当我尝试转换从feedd获取的发布日期时,我得到一个例外,因为日期是以下格式
'Wed, 5 May 2010 14:27:37 BST'
。
我尝试使用我在此处找到的代码段转换为Rfc822 datetime,但它仍然无效(因为显而易见的原因)。有谁知道如何将其转换为.Net
中的DateTime对象答案 0 :(得分:1)
“BST”及时意味着英国夏令时,巴西标准时间或白令海夏令时。如果您知道时间被“编码”的时区,您可以将其解析。我在我的样本中假设英国夏令时:
var date = DateTime.Parse("Wed, 5 May 2010 14:27:37", CultureInfo.GetCultureInfo("En-GB"));
从时间字符串的末尾“杀死”单词“BST”并获取英国文化信息以剔除日期和时间。
答案 1 :(得分:1)
我写了一个小片段,不支持所有格式,但很多。我很乐意收到反馈或改进......
/// <summary>
/// Parst ein Datum aus dem angegebenen XML Element.
/// Der Inhalt muss RFS 822, Kap. 5 entsprechen.
/// </summary>
/// <param name="current">Das Element mit dem RFS822-Datum (kann null sein, um null auszugeben)</param>
/// <returns>geparstes Datum oder null, wenn current==null ist.</returns>
/// <remarks>Unterstützt momentan die Zeitzonen-Angabe nur numerisch oder als UT/GMT, nicht als Mil-Zone oder TLA.</remarks>
private static DateTime? ParseRfc822DateTime(XElement current)
{
DateTime? result = null;
if (current != null)
{
Regex datePattern = new Regex(@"((Mon|Thu|Wed|Thu|Fri|Sat|Sun)\s*,\s*)?([0-9]{1,2})\s*(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s*([0-9]{2,4})\s*([0-9]{2}):([0-9]{2})(:([0-9]{2}))?(.*)", RegexOptions.Singleline);
Match match = datePattern.Match(current.Value);
if (match.Success)
{
string dayIndi = match.Groups[2].Value;
int day = int.Parse(match.Groups[3].Value);
string monText = match.Groups[4].Value;
int year = int.Parse(match.Groups[5].Value);
int hour = int.Parse(match.Groups[6].Value);
int min = int.Parse(match.Groups[7].Value);
int sec = match.Groups[8].Success ? int.Parse(match.Groups[9].Value) : 0;
string timezoneIndi = (match.Groups[10].Value ?? String.Empty).Trim();
if (year < 99)
{
year = System.Globalization.CultureInfo.InvariantCulture.Calendar.ToFourDigitYear(year);
}
result = DateTime.ParseExact(String.Format(
"{0:00}.{1}.{2:0000} {3:00}:{4:00}:{5:00}",
day, monText, year, hour, min, sec),
"dd.MMM.yyyy HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeLocal);
result = DateTime.SpecifyKind(result.Value, DateTimeKind.Unspecified);
TimeZoneInfo zoneInfo;
if (timezoneIndi == "UT" || timezoneIndi == "GMT")
{
zoneInfo = TimeZoneInfo.Utc;
}
else if (timezoneIndi.StartsWith("+") || timezoneIndi.StartsWith("-"))
{
int hoursOffset = int.Parse(timezoneIndi.Substring(1, 2));
int minsOffset = int.Parse(timezoneIndi.Substring(3, 2));
if (timezoneIndi.StartsWith("-"))
{
hoursOffset = -hoursOffset;
minsOffset = -minsOffset;
}
zoneInfo = TimeZoneInfo.CreateCustomTimeZone("RFC822-Offset" + timezoneIndi,
new TimeSpan(hoursOffset, minsOffset, 0), "RFS822-Offset" + timezoneIndi, timezoneIndi);
//result = result.Value.AddMinutes(minsOffset).AddHours(hoursOffset);
}
else
{
/* This WILL fail for the MIL-One-Letter-Zones and some others. */
zoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timezoneIndi);
}
result = TimeZoneInfo.ConvertTime(result.Value, zoneInfo, TimeZoneInfo.Local);
return result;
}
}
return result;
}