如何生成对应指定本地时间的UTC时间?代码实现咨询
问题:生成对应指定地点的UTC时间,确保客户端转换后显示预期本地时间
我需要生成一个与全球任意指定地点对应的UTC时间,要求客户端将其转换为本地时间后,能得到预期时间。举个具体例子:用户位于巴黎(UTC+1时区),要确保UX显示的时间为0300,那么JSON payload中应传入的UTC时间应为0200。
NextRunTime类包含需要表示的本地时间的小时和分钟,比如Hour为3、Minute为0,表示客户端转换后应显示0300本地时间;也可能是Hour为9、Minute为45的情况。
public class NextRunTime { public required int Hour { get; set; } public required int Minute { get; set; } public required string Type { get; set; } }
我刚着手编写相关代码,但对这类时间操作不太熟悉,写了如下扩展方法,不确定基础逻辑是否正确:
public static DateTime ToUtcOffsetFromBaseTime(this NextRunTime nextRunTime, Base? staffBase) { ArgumentNullException.ThrowIfNull(staffBase, nameof(staffBase)); var instant = DateTime.UtcNow.ToInstant(); var baseOffset = staffBase.OffsetAsOf(instant); if (baseOffset.HasValue) { // get the NOW local offset time var baseOffsetInstant = instant.WithOffset(baseOffset.Value); // set the local time to the next run time baseOffsetInstant.PlusHours(baseOffsetInstant.Hour - nextRunTime.Hour); baseOffsetInstant.PlusMinutes(baseOffsetInstant.Minute - nextRunTime.Minute); // offset it to the relative UTC time and return return baseOffsetInstant.ToDateTimeOffset().UtcDateTime; } throw new Exception($"The base offset for {staffBase.BaseCode} could not be found for the date/time {instant}."); }
我不确定现有代码的逻辑是否正确,也不知道后续该如何调整,希望得到指导。
内容的提问来源于stack exchange,提问作者Mike Perrenoud
相关产品推荐
相关产品推荐

