Q
: There are two MFC/ATL classes that encapsulate date and time: COleDateTime and CTime. Which one is better?
A
: Next are few arguments to prefer COleDateTime instead of CTime:
CTime keeps date between January 1, 1970 and December 31, 3000 (January 19, 2038 in older implementations). That is not enugh for most applications. For example, in a database may be persons born before 1970. COleDateTime can handle date between January 1, 100 and December 31, 9999 which is pretty much better. Example
Code:
// my birth date is
CTime t(1961, 8, 17); // August 17, 1961
CString strMyBirthDate = t.Format(_T("%m/%d/%Y"));
// results "01/08/1984"; I would like it to be truw, but it's not. :)
COleDateTime odt(1961, 8, 17, 0, 0, 0);
strMyBirthDate = odt.Format(_T("%m/%d/%Y"));
// results "08/17/1961", which is correct
COleDateTime has more powerful, flexible and easier to use Format functions, while CTime is limited to Format functins taking formatting specifiers. Example
Code:
CTime t(2007, 9, 11, 8, 25, 55);
// hard-coded date-time format (may be German)
CString strDateTime = t.Format(_T("%d.%m.%Y %H:%M:%S"));
// what about if English US, or Japanese, or another format is required at a moment?
// that's no sweat, by using COleDateTime:
COleDateTime odt(2007, 9, 11, 8, 25, 55);
LCID lcid = 0x409; // 0x409 is the locale ID for English US
strDateTime = odt.Format(0, lcid);
// and it's even easier if want to format according to user language set in Control Panel:
strDateTime = odt.Format();
COleDateTime has a ParseDateTime function while CTime has not. Example
Code:
COleDateTime odt;
// set odt value given a date-time string
odt.ParseDateTime(_T("9/12/2007 2:48:17 PM"), 0, 0x409);
// CTime has not such a member function
COleDateTime has Set functions (SetDate and SetDateTime) while CTime has not. Example
Code:
COleDateTime odt(2007, 10, 10, 0, 0, 0);
// sets a new value using SetDateTime:
odt.SetDateTime(2008, 11, 11, 11, 11, 11);
CTime t(2007, 10, 10, 0, 0, 0);
// sets a new value assigning a temporary CTime object, like dancing on the rope. :)
t = CTime(2008, 11, 11, 11, 11, 11);
COleDateTime is more precise when dealing with relative time periods. Example
Code:
COleDateTime odt(1970, 9, 30, 0, 0, 0);
odt += COleDateTimeSpan(31, 0, 0, 0);
CString strTime1 = odt.Format(_T("%d.%m.%Y %H:%M:%S"));
// results "31.10.1970 00:00:00" which is correct
CTime t(1970, 9, 30, 0, 0, 0);
t += CTimeSpan(31, 0, 0, 0);
CString strTime2 = t.Format(_T("%d.%m.%Y %H:%M:%S"));
// results "30.10.1970 23:00:00"
// one hour is missing, jumping back in the previous day
And may be others. The only one disadvantage of COleDateTime is that it introduces dependences to OLE libraries. As long as most MFC/ATL applications already use OLE stuff, this is not a big issue. from:http://forums.codeguru.com/showthread.php?503587-MFC-COleDateTime-vs-CTime-Which-one-is-better