如何解决为什么我的本地DateTime不转换为UTC?
我创建了一个本地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,则预期测试会失败。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。