在c ++中如何找到最大系统日期?

0 c++ time date

我试图在cpp中找到允许的最大系统日期,但我找不到这样做的功能......

谁能帮我?

Kir*_*sky 6

使用localtime功能.传递给它的值0numeric_limits<time_t>::max().对于不可接受的值,此函数将返回空指针.您可以使用二进制搜索算法更快地找到适当的值:O(log 2 N)其中N = numeric_limits<time_t>::max().

以下示例使用boost库,但它仍然与平台无关.如果不需要STL,你可以实现相同的功能.

#include <iostream>
#include <time.h>
#include <limits>
#include <algorithm>
#include <boost/iterator/counting_iterator.hpp>

using namespace std;
using namespace boost;

bool less_time( time_t val1, time_t val2 )
{
    tm* v1 = localtime( &val1 );
    tm* v2 = localtime( &val2 );
    if ( v1 && v2 ) return false;
    if ( !v1 && !v2 ) return false;
    if ( v1 && !v2) return true;
    return false;
};

int main() {
    counting_iterator<time_t> x = upper_bound( counting_iterator<time_t>(0), counting_iterator<time_t>(numeric_limits<time_t>::max()), 0, less_time );
    time_t xx = *x;
    --xx; // upper_bound gives first invalid value so we use previous one
    cout << "Max allowed time is: " << ctime(&xx) << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)