我现在不在我的代码前面,但我真的不认为我需要它来提出这个问题。所以我有一个倒计时器,每18小时关闭一次,然后重置。计时器检查当前DateTime.Now
并根据需要调整倒数计时器。我有一个问题,试图考虑到夏令时可以追溯到一小时后,因为;例如,2017年11月5日凌晨2点这个过去的事件可以追溯到凌晨1点,但是当我DateTime.IsDaylightSavingTime()
时,它告诉我即使夏令时刚刚结束也是假的。这使得我的计时器又回来了一个小时,因为它认为夏令时仍然没有发生在那一小时的时间段内。我该如何解决这个问题?
答案 0 :(得分:0)
我会使用DateTime.UtcNow你不会遇到夏令时问题
答案 1 :(得分:0)
如果由于某种原因您真的需要使用当地时间,那么您应该提前计算DST更改(事先安排下一个事件)。
TimeZoneInfo.GetAdjustmentRules()应该可以帮助您获得下一次DST调整的时间和增量。
以下是进行上调调整的代码:
public static DateTime? GetNextAdjustmentDate(TimeZoneInfo timeZoneInfo)
{
var adjustments = timeZoneInfo.GetAdjustmentRules();
if (adjustments.Length == 0)
{
return null;
}
int year = DateTime.UtcNow.Year;
TimeZoneInfo.AdjustmentRule adjustment = null;
foreach (TimeZoneInfo.AdjustmentRule adjustment1 in adjustments)
{
// Determine if this adjustment rule covers year desired
if (adjustment1.DateStart.Year <= year && adjustment1.DateEnd.Year >= year)
adjustment = adjustment1;
}
if (adjustment == null)
return null;
//TimeZoneInfo.TransitionTime startTransition, endTransition;
DateTime dstStart = GetCurrentYearAdjustmentDate(adjustment.DaylightTransitionStart);
DateTime dstEnd = GetCurrentYearAdjustmentDate(adjustment.DaylightTransitionEnd);
if (dstStart >= DateTime.UtcNow.Date)
return dstStart;
if (dstEnd >= DateTime.UtcNow.Date)
return dstEnd;
return null;
}
private static DateTime GetCurrentYearAdjustmentDate(TimeZoneInfo.TransitionTime transitionTime)
{
int year = DateTime.UtcNow.Year;
if (transitionTime.IsFixedDateRule)
return new DateTime(year, transitionTime.Month, transitionTime.Day);
else
{
// For non-fixed date rules, get local calendar
System.Globalization.Calendar cal = CultureInfo.CurrentCulture.Calendar;
// Get first day of week for transition
// For example, the 3rd week starts no earlier than the 15th of the month
int startOfWeek = transitionTime.Week * 7 - 6;
// What day of the week does the month start on?
int firstDayOfWeek = (int)cal.GetDayOfWeek(new DateTime(year, transitionTime.Month, 1));
// Determine how much start date has to be adjusted
int transitionDay;
int changeDayOfWeek = (int)transitionTime.DayOfWeek;
if (firstDayOfWeek <= changeDayOfWeek)
transitionDay = startOfWeek + (changeDayOfWeek - firstDayOfWeek);
else
transitionDay = startOfWeek + (7 - firstDayOfWeek + changeDayOfWeek);
// Adjust for months with no fifth week
if (transitionDay > cal.GetDaysInMonth(year, transitionTime.Month))
transitionDay -= 7;
return new DateTime(year, transitionTime.Month, transitionDay);
}
}
您需要添加更多代码才能检索并应用调整增量。
嗯 - 现在,当你看到所有需要完成的艰苦工作(而不是维护并确保无bug)时,你可能想要解决你的问题以便能够使用UTC < /强>