gpt4 book ai didi

.net - 使用 DotNet 在本地一天中的小时数

转载 作者:行者123 更新时间:2023-12-02 16:15:28 25 4
gpt4 key购买 nike

dotnet 中是否有任何内置的 api 可以告诉您指定的一天有多少小时?

这假设 API 将在给定时区内使用夏令时。因此,对于从格林威治标准时间进入夏令时的英国,白天将有 23 小时,而夏令时将有 25 小时回到格林威治标准时间。

我还没有在 nodatime 中发现任何东西直接执行此操作。

我可以在 NodaTime 中做类似下面的事情,但有没有更好的方法?

DateTimeZone london = DateTimeZoneProviders.Tzdb["Europe/London"];
LocalDate start = new LocalDate(2021, 3, 28);
LocalDate end = new LocalDate(2021, 3, 29);

ZonedDateTime startZ = london.AtStartOfDay(start);
ZonedDateTime endZ = london.AtStartOfDay(end);
ZonedDateTime dt = startZ;

int period = 1;

while (dt.ToInstant() < endZ.ToInstant())
{
testOutputHelper.WriteLine("Period: " + period + ", " + dt.ToString() + ", Hour: " + dt.Hour);

dt = dt.PlusHours(1);
period++;
}

最佳答案

是的,你绝对可以在 Noda Time 中更简单地做到这一点:

public static Duration GetDayDuration(LocalDate date, DateTimeZone zone)
{
var start = zone.AtStartOfDay(date);
var end = zone.AtStartOfDay(date.PlusDays(1));
return end - start;
}

这将返回一个 Duration,它是“耗时量”的 Noda Time 表示。您可以使用其中的 TotalHours 属性。 (使用 Hours 是错误的,因为 25 小时的持续时间将为 Hours 属性返回 1。)

完整示例:

using NodaTime;
using System;

class Test
{
static void Main()
{
DateTimeZone london = DateTimeZoneProviders.Tzdb["Europe/London"];
ShowDayDuration(new LocalDate(2021, 3, 28), london);
ShowDayDuration(new LocalDate(2021, 6, 19), london);
ShowDayDuration(new LocalDate(2021, 10, 31), london);
}

public static void ShowDayDuration(LocalDate date, DateTimeZone zone)
{
var duration = GetDayDuration(date, zone);
// Note: this truncation will give the result in rare cases,
// when the UTC offset changes by a fractional number of hours.
int hours = (int) duration.TotalHours;
Console.WriteLine($"Duration of {date} in zone {zone.Id}: {hours} hours");
}

public static Duration GetDayDuration(LocalDate date, DateTimeZone zone)
{
var start = zone.AtStartOfDay(date);
var end = zone.AtStartOfDay(date.PlusDays(1));
return end.ToInstant() - start.ToInstant();
}
}

关于.net - 使用 DotNet 在本地一天中的小时数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66866656/

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