gpt4 book ai didi

c++ - 比较日期的安全方法 (time_t)

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:35 26 4
gpt4 key购买 nike

我试图编写一个可移植函数来检查日期是否在我编写此实现但不起作用的范围内:

/**
* @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);

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

最佳答案

这里检查 date > 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;

如果日期 < 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;

关于c++ - 比较日期的安全方法 (time_t),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20071683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com