Introduction
In one of my projects I wanted to check if the given date is correct. I tried to find an appropriate API function, but could not find an appropriate function both in the C++ library, and in Platform SDK. Therefore I decided to create one on my own.
Using the code
The code is presented as one simple function. You should set the function parameters. The function returns true or false, depending on whether the date is valid.
bool IsDateValid( const int nDay, const int nMonth, const int nYear ) const
{
_ASSERT(nDay > 0);
_ASSERT(nMonth > 0);
_ASSERT(nYear > 0);
tm tmDate;
memset( &tmDate, 0, sizeof(tm) );
tmDate.tm_mday = nDay;
tmDate.tm_mon = (nMonth - 1);
tmDate.tm_year = (nYear - 1900);
tm tmValidateDate;
memcpy( &tmValidateDate, &tmDate, sizeof(tm) );
time_t timeCalendar = mktime( &tmValidateDate );
if( timeCalendar == (time_t) -1 )
return false;
return (
(tmDate.tm_mday == tmValidateDate.tm_mday) &&
(tmDate.tm_mon == tmValidateDate.tm_mon) &&
(tmDate.tm_year == tmValidateDate.tm_year) &&
(tmDate.tm_hour == tmValidateDate.tm_hour) &&
(tmDate.tm_min == tmValidateDate.tm_min) &&
(tmDate.tm_sec == tmValidateDate.tm_sec) );
}
Points of Interest
After some research I discovered that the ATL includes COleDateTime class, that has the GetStatus() method used for datetime checking. But after code investigation I discovered that the COleDateTime simply checks datetime range of values .
History
- 11.07.2003 - First version of the source code.