gpt4 book ai didi

c# - 如何在不转换时间的情况下更改 ZonedDateTime 的时区

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:42 24 4
gpt4 key购买 nike

我有一个 ZonedDateTime,它是我使用 DateTimeOffset 和一个时区 ID(字符串)创建的,我还有一个 DateTimeZone

我遇到的特殊情况是我需要更改 ZonedDateTime 的 Zone 而无需实际转换时间(即我有 18:00 UTC-4:00,我想将其更改为18:00 UTC-8 相应地转换 18:00)

我发现的唯一相关函数是 .WithZone(DateTimeZone) 但这似乎是根据提供的区域转换我的时间

如何在不转换时间的情况下更改 ZonedDateTime 的“时区”?

编辑我找到了一个似乎有效的解决方案:

private DateTimeOffset myFunction(DateTimeOffset dateTimeOffset, string timeZoneId) {
// get the DateTimeZone (i.e. Etc/GMT)
DateTimeZone timezone = DateTimeZoneProviders.Tzdb[timeZoneId];

// create a new DTO with the previous date/time values, but with the DateTimeZone Offset
var newDTO = new DateTimeOffset(dateTimeOffset.DateTime, timezone.GetUtcOffset(SystemClock.Instance.GetCurrentInstant()).ToTimeSpan());

// create a ZonedDateTime based on the new DTO
var nodaDTO = ZonedDateTime.FromDateTimeOffset(newDTO);

// the correct datetime in the correct zone
var finalProduct = nodaDTO.WithZone(timezone);

return finalProduct.ToDateTimeOffset();
}

最佳答案

如评论中所述,执行此操作的愿望通常表明上游有问题 - 如果您可以在那里修复它,您应该这样做。

如果您最终遇到 DateTimeOffset 的情况,其中本地部分绝对正确但偏移量不正确,并且您确实无法更早地修复数据,那么您将需要找到该本地时间的正确 UTC 偏移量。重要的是要注意本地时间可能不明确(如果它发生在“后退”转换期间)或被跳过(如果它发生在“向前跳转”转换期间),您应该弄清楚在这种情况下该怎么做。

您可以为此使用 DateTimeZone.MapLocal:

private DateTimeOffset myFunction(DateTimeOffset dateTimeOffset, string timeZoneId)
{
var unspecifiedDateTime = DateTime.SpecifyKind(dateTimeOffset.DateTime, DateTimeKind.Unspecified);
var zone = DateTimeZoneProviders.Tzdb[timeZoneId];
var local = LocalDateTime.FromDateTime(unspecifiedDateTime);
ZoneLocalMapping mapping = zone.MapLocal(local);
// Read documentation for details of this; you can easily detect the
// unambiguous/ambiguous/skipped cases here. You should decide what to do with them.
ZoneInterval mappedInterval = mapping.EarlyInterval;
TimeSpan bclOffset = mappedInterval.WallOffset.ToTimeSpan();
return new DateTimeOff(unspecifiedDateTime, bclOffset);
}

关于c# - 如何在不转换时间的情况下更改 ZonedDateTime 的时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56656931/

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