Recently I found myself needing a time picker that would show just the hours and minutes fields, without the
seconds. Since the common control has no built-in style to do this, I did the logical thing and wrote a snippet
of code to set a picker control to have such a format.
I also needed the code to work on any language and time format, so I delved into the SDK docs and read up on
GetLocaleInfo()
, which is the key to making the code work with all time formats.
The steps involved in this procedure are:
- Get the time separator (usually ':') and the current time format picture.
- Search for "ss" following the separator. This handles formats like "hh:mm:ss". If that
substring is found, delete it from the format picture and jump to step 4.
- Search for "s" following the separator. This handles formats like "hh:mm:s". If that substring
is found, delete it from the format picture.
- Set the time picker's format to the modified format we just created.
Note that this method doesn't care about the AM/PM indicator, if there is one. It will remain where it is in
the format picture.
This code was written in MSVC 6 on Win 98. I use CString::Delete()
(an
MFC 6 function) to remove characters, so it will require a bit of tweaking to run on VC 5. It should work fine
in Unicode, since I do everything with CString
s, although I haven't tested
it.
TCHAR szBuf[64];
CString sTimeFormat;
CString sSearch;
int nIndex;
CDateTimeCtrl* pTimeCtl;
VERIFY ( ::GetLocaleInfo ( LOCALE_USER_DEFAULT, LOCALE_STIMEFORMAT,
szBuf, 64 ));
sTimeFormat = szBuf;
VERIFY ( ::GetLocaleInfo ( LOCALE_USER_DEFAULT, LOCALE_STIME,
szBuf, 64 ));
sSearch = szBuf;
sSearch += _T("ss");
nIndex = sTimeFormat.Find ( sSearch );
if ( -1 != nIndex )
{
sTimeFormat.Delete ( nIndex, sSearch.GetLength() );
}
else
{
sSearch = szBuf;
sSearch += 's';
nIndex = sTimeFormat.Find ( sSearch );
if ( -1 != nIndex )
{
sTimeFormat.Delete ( nIndex, sSearch.GetLength() );
}
}
ASSERT_VALID(pTimeCtl);
VERIFY ( pTimeCtl->SetFormat ( sTimeFormat ));
Michael lives in sunny Mountain View, California. He started programming with an Apple
//e in 4th grade, graduated from
UCLA with a math degree in 1994, and immediately landed a job as a QA engineer at Symantec, working on the Norton AntiVirus team. He pretty much taught himself Windows and MFC programming, and in 1999 he designed and coded a new interface for Norton AntiVirus 2000.
Mike has been a a developer at
Napster and at his own lil' startup, Zabersoft, a development company he co-founded with offices in Los Angeles and Odense, Denmark. Mike is now a senior engineer at
VMware.
He also enjoys his hobbies of playing pinball, bike riding, photography, and Domion on Friday nights (current favorite combo: Village + double Pirate Ship). He would get his own snooker table too if they weren't so darn big! He is also sad that he's forgotten the languages he's studied: French, Mandarin Chinese, and Japanese.
Mike was a
VC MVP from 2005 to 2009.