CTimeSpan.GetDays () and Daylight Saving Time

I found an error in the old MFC MFC program that calculates the offset (in days) for a given date from a fixed base date. We saw results that were disabled for some reason, and I tracked it to where the original programmer used the CTimeSpan.GetDays () method. According to the documentation :

Please note that daylight saving time may cause GetDays to return a potentially unexpected result. For example, when a DST is in effect, GetDays reports the number of days from April 1 to May 1 as 29, not 30, because one day in April is reduced by an hour and therefore is not considered a full day.

My suggested fix is ​​to use (obj.GetTotalHours()+1)/24. I think this will cover all the problems, since this is a batch task that works at about the same time every day, but I thought I would ask smart people here before introducing it, if there could be a better way.

This is just a side issue, but I'm also interested in how this will be handled if the program can be launched at any time.

+3
source share
2 answers

Your fix works just fine to get the number of whole 24-hour periods between two moments - as long as the events happen at the same time every day. Otherwise, the expression "+1" in the expression may result in a "one by one" error.

, , , . , , :

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;
+2

, , - : CTime. ( ). -1, " , ".

// Discard hours, minutes, seconds, and daylight savings time
CTime startDay(start.GetYear(), start.GetMonth(), start.GetDay(), 0, 0, 0, 0);
CTime endDay(end.GetYear(), end.GetMonth(), end.GetDay(), 0, 0, 0, 0);

// Get number of days apart
CTimeSpan span = endDay - startDay;
int nDays = span.GetDays();

.

0

Source: https://habr.com/ru/post/1698804/


All Articles