Jon 的回答很棒,展示了 Noda Time 如何让这些操作变得简单。
但是,由于问题还询问了内置 API,为了完整起见,我将展示一种不需要 Noda Time 的替代方法。
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
public class Program
{
public static void Main()
{
// Note, the following line is just an example for clarity. If you know which form of identifier your platform supports
// or are using TimeZoneConverter, or are using .NET 6+ (which will have conversions built-in), then you can just use the appropriate simple string.
string tzid = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "GMT Standard Time" : "Europe/London";
// Get the time zone and show a few different days and their duration.
TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(tzid);
ShowDayDuration(new DateTime(2021, 3, 28), zone);
ShowDayDuration(new DateTime(2021, 6, 19), zone);
ShowDayDuration(new DateTime(2021, 10, 31), zone);
}
public static void ShowDayDuration(DateTime date, TimeZoneInfo zone)
{
TimeSpan duration = GetDayDuration(date, zone);
Console.WriteLine($"Duration of {date:yyyy-MM-dd} in zone {zone.Id}: {duration.TotalHours} hours");
}
public static TimeSpan GetDayDuration(DateTime date, TimeZoneInfo zone)
{
// Just to make sure the input value is strictly a date with the time truncated.
Debug.Assert(date.Kind == DateTimeKind.Unspecified);
Debug.Assert(date.TimeOfDay == TimeSpan.Zero);
// Subtract the start of the given date and the subsequent date.
DateTimeOffset dto1 = GetStartOfDay(date, zone);
DateTimeOffset dto2 = GetStartOfDay(date.AddDays(1), zone);
return dto2 - dto1;
}
public static DateTimeOffset GetStartOfDay(DateTime date, TimeZoneInfo zone)
{
// Just to make sure the input value is strictly a date with the time truncated.
Debug.Assert(date.Kind == DateTimeKind.Unspecified);
Debug.Assert(date.TimeOfDay == TimeSpan.Zero);
TimeSpan offset;
if (zone.IsAmbiguousTime(date))
{
// When the date/time is ambiguous, use the larger of the two offsets because the resulting value will come first sequentially.
offset = zone.GetAmbiguousTimeOffsets(date).Max();
}
else
{
// When the date/time is invalid, find the next valid time. Search by 15 minute increments to accomodate oddities of various time zones.
while (zone.IsInvalidTime(date))
{
date = date.AddMinutes(15);
}
offset = zone.GetUtcOffset(date);
}
return new DateTimeOffset(date, offset);
}
}
Working fiddle here.
输出:
Duration of 2021-03-28 in zone Europe/London: 23 hours
Duration of 2021-06-19 in zone Europe/London: 24 hours
Duration of 2021-10-31 in zone Europe/London: 25 hours
如您所见,Noda Time 的类型系统和内置的AtStartOfDay 方法使 Noda Time 成为一个更简单的选择,但仍然可以仅使用内置类型获得正确答案。