gpt4 book ai didi

C# DateTime - 将 DateTimeOffset 转换为另一个时区

转载 作者:行者123 更新时间:2023-12-05 09:09:26 27 4
gpt4 key购买 nike

将 DateTimeOffset 转换为另一个 TimeZone 时,OffSet 不正确。

我已经阅读了很多文章并试验了太多小时,但看不到我在这里遗漏了什么:

// It's June in the UK and we're in British Summer Time, which is 1 hour ahead of UTC (GMT)
var UKoffsetUtc = new TimeSpan(1, 0, 0);

// It's 4pm - declare local time as a DateTimeOffset
var UKdateTimeOffset = new DateTimeOffset(2020, 6, 17, 16, 0, 0, UKoffsetUtc);

// Convert to UTC as a date
var utc = DateTime.SpecifyKind(UKdateTimeOffset.UtcDateTime, DateTimeKind.Utc);

// Get Aus TimeZoneInfo
var AUSTimeZone = TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time");

// Check the Aus offset from UTC
var AUSOffset = AUSTimeZone.GetUtcOffset(utc);
Console.WriteLine(AUSOffset); // Output is 10 as expected

// Declare Aus Time as DateTimeOffset
var AUSDateTimeOffset = TimeZoneInfo.ConvertTimeFromUtc(utc, AUSTimeZone);

// The Aus Offset from UTC is not correct
Console.WriteLine(AUSDateTimeOffset.ToString("dd MM yyyy HH:mm zzz"));

输出为 18 06 2020 01:00 +01:00

澳大利亚比 UTC 早 10 小时(比 GMT 早 9 小时),因此日期和时间是正确的,但不是偏移量。

如何在 AUSDateTimeOffset 中获得正确的偏移量?

最佳答案

您可以创建新的偏移量并使用它 -

    // Create new offset for UTC
var AUSOffset = new DateTimeOffset(utc, TimeSpan.Zero);

// Declare Aus Time as DateTimeOffset
var AUSDateTimeOffset = UKdateTimeOffset.ToOffset(AUSTimeZone.GetUtcOffset(AUSOffset));
Console.WriteLine(AUSDateTimeOffset.ToString("dd MM yyyy HH:mm zzz"));

或者:

使用ConvertTimeBySystemTimeZoneId正如 Jimi 在评论中所建议的那样!

    var finalDate = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(UKdateTimeOffset, "AUS Eastern Standard Time");
Console.WriteLine(finalDate.ToString("dd MM yyyy HH:mm zzz"));

关于C# DateTime - 将 DateTimeOffset 转换为另一个时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62433342/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com