我将把and 1123-dateformat转换为DateTime对象,反之亦然。RFC-日期-字符串的DateTime对象工作得很好,但是由于我生活在德国(MEZ- Timezone),我得到了错误的结果。
因此,有一次,这里是我的转换类:
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点。
发布于 2017-12-18 08:54:40
好的,我看到我犯了一个错误:我需要将时区设置为CET,而不是GMT,因为我在德国,也就是CET (或GMT+1)。所以这个函数是正确的。
https://stackoverflow.com/questions/36107690
复制相似问题