将日期时间格式从 RFC1123 转换为日期时间对象
Convert datetime-format from RFC1123 to DateTime-Object
我正在将 RFC1123-dateformat 转换为 DateTime-Object,反之亦然。 RFC-date-string 的 DateTime-Object 工作得很好,但因为我住在德国 (MEZ- Timezone),所以我得到了错误的结果。
所以一次,这是我的 class 转换:
public interface IRFCDate
{
DateTime ToDateTime();
}
public class RFCDate : IRFCDate
{
private string dateString { get; set; } = null;
private DateTime? dateObject { get; set; } = null;
public DateTime ToDateTime()
{
if (dateObject.HasValue) return dateObject.Value;
string regexPattern = @"[a-zA-Z]+, [0-9]+ [a-zA-Z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+ (?<timezone>[a-zA-Z]+)";
Regex findTimezone = new Regex(regexPattern, RegexOptions.Compiled);
string timezone = findTimezone.Match(dateString).Result("${timezone}");
string format = $"ddd, dd MMM yyyy HH:mm:ss {timezone}";
dateObject = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
return dateObject.Value;
}
public IRFCDate From(IConvertible value)
{
if (value is string)
dateString = value.ToString();
else if (value is DateTime)
dateObject = (DateTime)value;
else
throw new NotSupportedException($"Parametertype has to be either string or DateTime. '{value.GetType()}' is unsupported.");
return this;
}
}
我的 Xunit-Testcase 看起来像这样:
[Fact]
public void StringToDateTime()
{
DateTime expectedValue = new DateTime(2001, 1, 1);
string RFCDatestring = "Mon, 01 Jan 2001 00:00:00 GMT";
DateTime actualValue = RFCDatestring.To<DateTime>();
Assert.Equal(expectedValue, actualValue);
}
在这种情况下调用
return new RFCDate().From(@this).ToDateTime();
所以执行我的测试用例时的结果是:
Assert.Equal() Failure
Expected: 2001-01-01T00:00:00.0000000
Actual: 2001-01-01T01:00:00.0000000+01:00
有人知道如何解决这个问题吗?实际值应该是 00:00 点,而不是 1 点。
好的,我发现我犯了一个错误:我需要将时区设置为 CET
而不是 GMT
,因为我在德国,这是 CET(或 GMT+1)。
所以函数是正确的。