65.9K
CodeProject 正在变化。 阅读更多。
Home

如何检查日期时间是否存在

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.55/5 (11投票s)

2003年8月8日

viewsIcon

66806

一篇关于检查日期时间的文章

引言

在一个项目中,我想检查给定的日期是否有效。我尝试寻找合适的 API 函数,但没有在 C++ 库或平台 SDK 中找到合适的函数。因此,我决定自己创建一个。

Using the Code

代码呈现为一个简单的函数。您应该设置函数参数。该函数返回 truefalse,具体取决于日期是否有效。

///
/// 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) );
}

关注点

经过一些研究,我发现 ATL 包含 COleDateTime 类,该类具有用于 datetime 检查的 GetStatus() 方法。但经过代码调查,我发现 COleDateTime 只是检查 datetime 值的范围。

历史

  • 2003年7月11日 - 源代码的第一个版本

许可证

本文未附加明确的许可证,但可能在文章文本或下载文件本身中包含使用条款。如有疑问,请通过下面的讨论区联系作者。

作者可能使用的许可证列表可以在此处找到。

© . All rights reserved.