I create a local DateTime where the offset should be 00:01:00 (GMT Standard Time). However when converting to UTC it merely specifies the kind as UTC, and doesn't actually convert it.
[Test]
public void GivenLocalDateTime_WhenConverted_ThenBecomesUtc()
{
// Arrange
var local = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Local);
var expected = new DateTime(2019, 12, 31, 23, 0, 0, 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
*/
}
I've tried several routes. Using TimeZoneInfo...
var result = TimeZoneInfo.ConvertTimeToUtc(local, TimeZoneInfo.Local);
And parsing it as a string...
var result = DateTime.Parse(local.ToString("O"), CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal);
None of these work. I feel like all of these should work. What am I missing?
This verifies that you are currently (August) 1 hour ahead of UTC:
Assert.AreEqual(DateTimeOffset.Now.Offset, TimeSpan.FromHours(1)); // Passes
While the actual test converts a date in January when there is probably a different UTC offset. So if you have configured DST, it is expected that your test fails.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.