|
|
QA: How can I convert CTime object to string?
By Yaroslav Goncharov, November 21, 2001.
Print version
Question
I need to convert CTime object to the string. I have noted that MFC for Windows CE did not support CTime::Format method. What methods should I use?
Answer
You can use GetDateFormat and GetTimeFormat system functions. You can use a custom format or a system default one. The following functions convert CTime object to string using default system format.
// formats date to string using the default system locale
CString FormatDate(CTime time)
{
// get time in system time format
SYSTEMTIME st;
time.GetAsSystemTime(st);
// get necessary buffer size
int nSize = GetDateFormat(
LOCALE_SYSTEM_DEFAULT,
LOCALE_NOUSEROVERRIDE,
&st,
NULL,
NULL,
0);
// format the date
CString strDate;
GetDateFormat(
LOCALE_SYSTEM_DEFAULT,
LOCALE_NOUSEROVERRIDE,
&st,
NULL,
strDate.GetBuffer(nSize),
nSize);
strDate.ReleaseBuffer();
return strDate;
}
// formats time to string using the default system locale
CString FormatTime(CTime time)
{
// get time in system time format
SYSTEMTIME st;
time.GetAsSystemTime(st);
// get necessary buffer size
int nSize = GetTimeFormat(
LOCALE_SYSTEM_DEFAULT,
LOCALE_NOUSEROVERRIDE,
&st,
NULL,
NULL,
0);
// format the time
CString strTime;
GetTimeFormat(
LOCALE_SYSTEM_DEFAULT,
LOCALE_NOUSEROVERRIDE,
&st,
NULL,
strTime.GetBuffer(nSize),
nSize);
strTime.ReleaseBuffer();
return strTime;
}
Another possible (and much more simple) solution is to use COleDateTime class instead:
COleDateTime t(1999, 3, 19, 22, 15, 0);
CString str = t.Format(_T("%A, %B %d, %Y"));
ASSERT(str == _T("Friday, March 19, 1999"));
CString strTime = t.Format(VAR_TIMEVALUEONLY);
This class also handles wider range of times than CTime: it handles dates
from 1 January 100 - 31 December 9999 (See MSDN for details).
Related resources:
Discuss
Discuss this article.
Here you can write your comments and read comments of other developers.
|