Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Check if a datetime Exists

0.00/5 (No votes)
7 Aug 2003 1  
An article about checking a datetime

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.

///
/// Checks if the datetime exists.
/// nDay - <PARAM name="nDay">The day of month from 1 to 31.</PARAM>
/// nMonth - <PARAM name="nMonth">The month from 1 to 12.</PARAM>
/// nYear - <PARAM name="nYear">The years by Gregorian calendar.
/// </PARAM>
/// Returns true if date is correct, otherwise false.
///
bool IsDateValid( const int nDay, const int nMonth, const int nYear ) const
{
    _ASSERT(nDay > 0);
    _ASSERT(nMonth > 0);
    _ASSERT(nYear > 0);

    // check date existing
    tm tmDate;
    memset( &tmDate, 0, sizeof(tm) );
    tmDate.tm_mday = nDay;
    tmDate.tm_mon = (nMonth - 1);
    tmDate.tm_year = (nYear - 1900);

    // copy the entered date to the validate date structure
    tm tmValidateDate;
    memcpy( &tmValidateDate, &tmDate, sizeof(tm) );

    // If timeptr references a date before midnight, 
    // January 1, 1970, or if the calendar time cannot be 
    // represented, mktime returns –1 cast to type time_t.
    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

License

This article has no explicit license attached to it, but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below.

A list of licenses authors might use can be found here.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here