我正在将 RFC1123-dateformat 转换为 DateTime-Object,反之亦然。DateTime-Object 到 RFC-date-string 的效果很好,但由于我住在德国(MEZ-时区),我得到了错误的结果。
所以有一次,这是我的转换类:
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() 失败
预计:2001-01-01T00:00:00.0000000
实际:2001-01-01T01:00:00.0000000+01:00
有人知道如何解决这个问题吗?实际值应该是 00:00 点而不是 1 点。