问题描述
我创建了一个本地DateTime,偏移量应为00:01:00(格林尼治标准时间)。但是,在转换为UTC时,它仅将类型指定为UTC,而实际上并未将其转换。
[Test]
public void GivenLocalDateTime_WhenConverted_ThenBecomesUtc()
{
// Arrange
var local = new DateTime(2020,1,DateTimeKind.Local);
var expected = new DateTime(2019,12,31,23,DateTimeKind.Utc);
// Act
var result = local.ToUniversalTime();
// Assert
Assert.AreEqual(DateTimeOffset.Now.Offset,TimeSpan.FromHours(1)); // Passes
Assert.AreEqual(expected.Kind,result.Kind); // Passes
Assert.AreEqual(expected,result); // Fails
/*
Expected: 2019-12-31 23:00:00
But was: 2020-01-01 00:00:00
*/
}
我尝试了几种路线。使用TimeZoneInfo ...
var result = TimeZoneInfo.ConvertTimetoUtc(local,TimeZoneInfo.Local);
并将其解析为字符串...
var result = DateTime.Parse(local.ToString("O"),CultureInfo.InvariantCulture,DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal);
这些都不起作用。我觉得所有这些都应该起作用。我想念什么?
解决方法
这将证明您当前是当前时间(八月)比UTC早1小时:
Assert.AreEqual(DateTimeOffset.Now.Offset,TimeSpan.FromHours(1)); // Passes
尽管实际测试会转换可能存在不同UTC偏移量的1月的日期。因此,如果已配置DST,则预期测试会失败。