如何将判断CST时段的startDate与endDate设为中部标准时间?
解决方法
你的问题出在创建startDate和endDate时,硬编码了UTC偏移量(new TimeSpan(0, 0, 0)),导致这两个时间并不是中部标准时间(CST)时区的时间。要让它们使用CST的时区偏移,只需要复用currentDateInCST的偏移量即可——因为currentDateInCST已经是转换后的CST时间,它的Offset属性就是当前CST对应的UTC偏移(注意CST包含夏令时,偏移可能是-5或-6小时)。
另外你的GetTimeByTimeZone函数里有个笔误:参数是date,但代码里用了effectiveDate.Value,需要修正为date.Value,否则会编译报错。
修改后的完整代码如下:
public DateTimeOffset GetTimeByTimeZone(DateTimeOffset? date, string windowsTimeZone) { var timeZone = PlatformTimeZoneMapper.GetTimeZoneIdForPlatform(windowsTimeZone); var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone); // 修正笔误:effectiveDate改为date return date.Value.ToOffset(timeZoneInfo.GetUtcOffset(date.Value)); } var currentDateInCST = GetTimeByTimeZone(DateTimeOffset.Now, "Central Standard Time"); // 使用currentDateInCST的Offset作为时区偏移 var startDate = new DateTimeOffset(currentDateInCST.Year, currentDateInCST.Month, currentDateInCST.Day, 22, 0, 0, currentDateInCST.Offset); var tomorrowsDate = currentDateInCST.DateTime.AddDays(1); // 同样使用CST的偏移量 var endDate = new DateTimeOffset(tomorrowsDate.Year, tomorrowsDate.Month, tomorrowsDate.Day, 2, 0, 0, currentDateInCST.Offset); if (currentDateInCST >= startDate && currentDateInCST <= endDate) { // 执行你的逻辑 }
额外严谨方案
如果想完全脱离currentDateInCST的偏移依赖,直接通过时区信息创建标准的CST时间,可以这样写:
// 获取CST时区信息 var cstTimeZone = TimeZoneInfo.FindSystemTimeZoneById(PlatformTimeZoneMapper.GetTimeZoneIdForPlatform("Central Standard Time")); // 创建当天22:00的CST本地时间 var startLocalTime = new DateTime(currentDateInCST.Year, currentDateInCST.Month, currentDateInCST.Day, 22, 0, 0); // 转换为带正确偏移的DateTimeOffset var startDate = TimeZoneInfo.ConvertTime(startLocalTime, cstTimeZone); // 处理次日2:00的CST时间 var endLocalTime = startLocalTime.AddDays(1).AddHours(4); var endDate = TimeZoneInfo.ConvertTime(endLocalTime, cstTimeZone);
这种方式会自动处理夏令时切换带来的偏移变化,避免手动设置偏移可能出现的误差。
内容的提问来源于stack exchange,提问作者Utsab
相关产品推荐
相关产品推荐

