比较日期的安全方式(time_t)

时间:2013-11-19 12:31:32

标签: c++ c

我正在尝试编写一个便携式函数,用于检查日期是否在我编写此实现的范围内但不起作用:

/**
 * @brief teIsDateInRange checks if a date is inside a range of dates
 *        teIsDateRange checks if date is in [firstDate, endDate]
 * @param firstDate first date of the range
 * @param lastDate last date of the range
 * @param date date to check
 * @return 0 if the date is in the range, 1 if date is greater then lastDate or
 *         -1 if date is less than firstDate
 */
TMEXT_API int TMEXT_CALL teIsDateInRange( time_t firstDate, time_t lastDate, time_t date )
{
    const auto diff1 = std::difftime( firstDate, date );

    if ( diff1 > 0.0 ) return -1;
    if ( diff1 == 0.0 ) return 0;

    // we are sure that date is greater then firstDate now check upper range
    const auto diff2 = std::difftime( date, lastDate );
    if ( diff2 >= 0.0 ) return 0;
    else return 1;
}

我写了一个简单的测试套件,但测试失败

// main.cpp
#define BOOST_TEST_MODULE timeext_test_unit
#include <timeext/timeext.h>            // function where is defined teIsDateInRange

#include <utility/diagnostic.h>
// stop warnings on mingw with boost 1.55.0
GCC_DIAG_STOP
GCC_DIAG_OFF(unused-local-typedefs)
#include <boost/test/included/unit_test.hpp>
GCC_DIAG_START

#include <iostream>
using namespace std;


BOOST_AUTO_TEST_SUITE( test_suite1 )

BOOST_AUTO_TEST_CASE( test_case1 )
{
    const time_t first = time( nullptr );
    const time_t last = first + 500;
    const time_t d1 = first - 50;
    const time_t d2 = first + 40;
    const time_t d3 = first + 600;

    const auto r1 = teIsDateInRange( first, last, d1 );
    const auto r2 = teIsDateInRange( first, last, d2 );
    const auto r3 = teIsDateInRange( first, last, d3 );

    BOOST_REQUIRE( r1 == -1 );
    BOOST_REQUIRE( r2 ==  0 );      // <--- line 30: fail
    BOOST_REQUIRE( r3 ==  1 );
}

BOOST_AUTO_TEST_SUITE_END()

这是测试套件的输出:

Running 1 test case...
main.cpp(30): fatal error in "test_case1": critical check r2 == 0 failed

*** 1 failure detected in test suite "timeext_test_unit"

通过测试的方法是以这种方式重新实现该功能但不可移植:

TMEXT_API int TMEXT_CALL teIsDateInRange( time_t firstDate, time_t lastDate, time_t date )
{
    if ( date < firstDate )
        return -1;

    if ( date > lastDate )
        return 1;

    return 0;
}

有人知道一种可移植的方式来检查日期是否在某个范围内吗?

修改 difftime声明的另一个问题如下:

double difftime (time_t end, time_t beginning);

这似乎假设结束比开始更大。在我的情况下,我不知道结束是否比开始更大。

2 个答案:

答案 0 :(得分:2)

在这里检查日期&gt; lastDate,在这种情况下,你返回0:

// we are sure that date is greater then firstDate now check upper range
const auto diff2 = std::difftime( date, lastDate );
if ( diff2 >= 0.0 ) return 0;

如果日期&lt;

你应该返回0 lastDate:

// we are sure that date is greater then firstDate now check upper range
const auto diff2 = std::difftime( date, lastDate );
if ( diff2 <= 0.0 ) return 0;

答案 1 :(得分:1)

如果date < lastDate,您的第二次测试将返回1。如果date > lastDate,您希望返回1,即

const auto diff2 = std::difftime( date, lastDate );
if ( diff2 > 0.0 ) return 1;
else return 0;