You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中获取明日中部标准时间7点的DateTimeOffset值

代码正确性分析与优化方案

你的这段代码只有当当前系统时区正好是中部标准时间(CST/CDT)时才正确,其他情况都会出错,问题出在这两点:

  • DateTime.Now取的是系统本地时间,以此算出的「明天」是本地时区的明天,不是中部时区的明天
  • 构造tomorrowDate时标记为Local时区,但你实际要的是中部时区的7点,时区不匹配的话,后续计算的偏移量会完全偏离预期

更简便且准确的写法

基础版(Windows平台)

// 获取中部时区对象
var centralTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");

// 先拿UTC时间的明天,转成中部时区后取日期,再构造当天7点的时间
var tomorrowInCentral = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow.AddDays(1), centralTimeZone);
var targetTime = new DateTime(tomorrowInCentral.Year, tomorrowInCentral.Month, tomorrowInCentral.Day, 7, 0, 0);

// 转换为DateTimeOffset
var targetOffset = new DateTimeOffset(targetTime, centralTimeZone.GetUtcOffset(targetTime));

精简版

var centralTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var targetOffset = new DateTimeOffset(
    TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow.Date.AddDays(1), centralTimeZone).Date.AddHours(7),
    centralTimeZone.GetUtcOffset(DateTime.MinValue)
);

跨平台兼容版

如果代码需要在Linux/macOS等平台运行,建议用IANA标准时区ID"America/Chicago",可以借助TimeZoneConverter库实现跨平台兼容:

// 先安装TimeZoneConverter NuGet包
var centralTimeZone = TZConvert.GetTimeZoneInfo("America/Chicago");
var utcTomorrowDate = DateTime.UtcNow.Date.AddDays(1);
var centralTomorrowDate = TimeZoneInfo.ConvertTimeFromUtc(utcTomorrowDate, centralTimeZone).Date;
var targetOffset = new DateTimeOffset(centralTomorrowDate.AddHours(7), centralTimeZone.GetUtcOffset(centralTomorrowDate));

内容的提问来源于stack exchange,提问作者Utsab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 13:35:19