PRB: CTimeSpan::GetDays() Reports 29 Days in AprilLast reviewed: May 28, 1997Article ID: Q109790 |
The information in this article applies to:
SYMPTOMSThe CTimeSpan::GetDays function seems to incorrectly report that the number of days between April 1 and May 1 is 29, instead of 30.
CAUSEThis behavior of the CTimeSpan::GetDays function is by design. One day in April is the start of Daylight Savings Time. On that day, there are only 23 hours, instead of the normal 24. Because of the way the CTimeSpan::GetDays member function is implemented, a day with less than 24 hours is not a complete day. Because the time span is figured in seconds, the time span for a month is the sum of all the seconds in a month. The definition of CTimeSpan::GetDays() in AFX.INL (located in the MFC\INCLUDE sub-directory of the Visual C++ installation directory)calculates the number of days by dividing the value of the m_timeSpan member variable by the number of seconds in a day. Thus, if one day in a 30-day month has 23 hours (which is the case here), m_timeSpan will be short by 3600 seconds, and the result of the division will be 29 (days), rather than 30. This is a characteristic of integer division in C/C++ where the remainder is truncated.
RESOLUTIONThere are two workarounds:
Sample Code
void CDialogsApp::OnTimeDaysInApril() { // Set TZ environment variable. if (_putenv("TZ=PST8")==-1) // Can't set variable. AfxMessageBox("Unable to set TZ environment variable",MB_OK); else { // Variable set, show its effect! CTime t1(1993,4,1,0,0,0); // April 1, 1993, 12:00:00 am CTime t2(1993,5,1,0,0,0); // May 1, 1993, 12:00:00 am // Calculate time span. CTimeSpan ts = t2 - t1; LONG lNumDays=ts.GetDays(); // Output message. char buffer[40]; wsprintf(buffer,"Days in April: %ld",lNumDays); AfxMessageBox(buffer,MB_OK); } } |
Keywords : MfcMisc kbprb
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |