Get long or short date and time from CTime MFC class ( C++)



Often we have to show date/time to the user in our program. If you have enough screen space, it is better to show it in long date time format. Following is the code to get long or short date and time from CTime MFC class ( C++) in Windows.

 
CString	FormatLocaleDateTime(CTime tm, bool longDate /*= false*/)
{
	CString value;
 
	if (longDate) {
		value.Format(_T("%s %s"), FormatLocaleLongDate(tm), FormatLocaleTime(tm));
	}
	else {
		value.Format(_T("%s %s"), FormatLocaleShortDate(tm), FormatLocaleTime(tm));
	}
 
	return value;
}
 
CString	FormatLocaleShortDate(CTime tm)
{
	CString strValue;
	SYSTEMTIME st;
	tm.GetAsSystemTime(st);
	GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st, NULL, strValue.GetBufferSetLength(SMALL_TEXT_LENGTH), SMALL_TEXT_LENGTH);
	strValue.ReleaseBuffer();
	return strValue;
}
 
CString	FormatLocaleLongDate(CTime tm)
{
 
	CString strValue;
	SYSTEMTIME st;
	tm.GetAsSystemTime(st);
	GetDateFormat(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, strValue.GetBufferSetLength(SMALL_TEXT_LENGTH), SMALL_TEXT_LENGTH);
	strValue.ReleaseBuffer();
	return strValue;
 
}
 
CString	FormatLocaleTime(CTime tm)
{
 
	CString strValue;
	SYSTEMTIME st;
	tm.GetAsSystemTime(st);
	GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &st, NULL, strValue.GetBufferSetLength(SMALL_TEXT_LENGTH), SMALL_TEXT_LENGTH);
	strValue.ReleaseBuffer();
	return strValue;
 
}


Leave a Reply

Your email address will not be published. Required fields are marked *