gpt4 book ai didi

c# - Noda Time - 从 DateTime 和 TimeZoneId 创建 ZonedDateTime

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

假设我有以下日期、时间和时区:2016-10-15, 1:00:00, America/Toronto

如何创建一个 ZonedDateTime 来表示指定区域中的确切日期和时间?

基本上,我需要一个 ZonedDateTime 对象来表示准确时区中的准确日期和时间。

如果时间被跳过,我想在新时间上加上小时的滴答声。示例:

如果从 00:00 跳到 1:00,并且我尝试获取区域中的时间 00:30,我希望结果是 1:30,而不仅仅是 1:00,这是第一次间隔。

如果从 00:00 跳到 1:45,并且我尝试获取该区域中的时间 00:20,我希望结果为 2:05。

如果时间不明确,i. e., 出现两次,我想要早期的映射。

最佳答案

您所描述的正是 Noda Time 2.0 中 LocalDateTime.InZoneLeniently 的行为。 (感谢 Matt Johnson's change :) 然而,由于它仍处于 alpha 阶段,这里是 1.3.2 的解决方案。基本上,您只需要一个合适的 ZoneLocalMappingResolver,您可以使用 Resolvers 构建它.这是一个完整的示例。

using NodaTime.TimeZones;
using NodaTime.Text;

class Program
{
static void Main(string[] args)
{
// Paris went forward from UTC+1 to UTC+2
// at 2am local time on March 29th 2015, and back
// from UTC+2 to UTC+1 at 3am local time on October 25th 2015.
var zone = DateTimeZoneProviders.Tzdb["Europe/Paris"];

ResolveLocal(new LocalDateTime(2015, 3, 29, 2, 30, 0), zone);
ResolveLocal(new LocalDateTime(2015, 6, 19, 2, 30, 0), zone);
ResolveLocal(new LocalDateTime(2015, 10, 25, 2, 30, 0), zone);
}

static void ResolveLocal(LocalDateTime input, DateTimeZone zone)
{
// This can be cached in a static field; it's thread-safe.
var resolver = Resolvers.CreateMappingResolver(
Resolvers.ReturnEarlier, ShiftForward);

var result = input.InZone(zone, resolver);
Console.WriteLine("{0} => {1}", input, result);
}

static ZonedDateTime ShiftForward(
LocalDateTime local,
DateTimeZone zone,
ZoneInterval intervalBefore,
ZoneInterval intervalAfter)
{
var instant = new OffsetDateTime(local, intervalBefore.WallOffset)
.WithOffset(intervalAfter.WallOffset)
.ToInstant();
return new ZonedDateTime(instant, zone);
}
}

输出:

29/03/2015 02:30:00 => 2015-03-29T03:30:00 Europe/Paris (+02)
19/06/2015 02:30:00 => 2015-06-19T02:30:00 Europe/Paris (+02)
25/10/2015 02:30:00 => 2015-10-25T02:30:00 Europe/Paris (+02)

关于c# - Noda Time - 从 DateTime 和 TimeZoneId 创建 ZonedDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40184589/

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