我在一个旧的 C++ MFC 程序中发现了一个错误,该程序计算给定日期相对于固定基准日期的偏移量(以天为单位)。由于某种原因,我们看到的结果有一个偏差,我追踪到原始程序员使用 CTimeSpan.GetDays() 方法的地方。根据documentation :
Note that Daylight Savings Time can cause GetDays to return a potentially surprising result. For example, when DST is in effect, GetDays reports the number of days between April 1 and May 1 as 29, not 30, because one day in April is shortened by an hour and therefore does not count as a complete day.
我建议的修复方法是改用 (obj.GetTotalHours()+1)/24
。我认为这将涵盖所有问题,因为这是一个每天大约在同一时间运行的批处理作业,但我想我会在实现之前询问这里的聪明人是否有更好的方法。
这只是一个附带问题,但我也很好奇如果程序可以随时运行,将如何处理。
最佳答案
您的修复可以很好地获取两次之间整个 24 小时周期的数量 - 只要事件每天都在同一时间发生。否则表达式中的“+1”可能会导致差一错误。
有时您并不关心事件发生在一天中的什么时间,您只想知道是哪一天。在这种情况下,您需要将小时、分钟和秒归零,然后使用您的公式:
CTime startDay(start.GetYear(), start.GetMonth(), start.GetDay(), 0, 0, 0);
CTime finishDay(finish.GetYear(), finish.GetMonth(), finish.GetDay(), 0, 0, 0);
int days = ((finishDay - startDay).GetTotalHours() + 1) / 24;
关于c++ - CTimeSpan.GetDays() 和夏令时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/243568/