I'm trying to find the maximum allowed system date in cpp, but I can't find the function to do that...
我试图在cpp中找到允许的最大系统日期,但我找不到这样做的功能......
Can anyone help me?
谁能帮我?
2 个解决方案
#1
Use localtime
function. Pass to it values from 0
to numeric_limits<time_t>::max()
. For unacceptable values this function will return null pointer. You could use binary search algorithm to find appropriate value faster: O(log2 N) where N = numeric_limits<time_t>::max()
.
使用本地时间功能。传递给它的值从0到numeric_limits
The following sample uses boost library, but it still platform independent. You could implement the same without STL or boost if it is required.
以下示例使用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;
}
#2
Would depend on the OS, are we using windows or something POSIX compliant here?
将取决于操作系统,我们在这里使用Windows或POSIX兼容吗?
#1
Use localtime
function. Pass to it values from 0
to numeric_limits<time_t>::max()
. For unacceptable values this function will return null pointer. You could use binary search algorithm to find appropriate value faster: O(log2 N) where N = numeric_limits<time_t>::max()
.
使用本地时间功能。传递给它的值从0到numeric_limits
The following sample uses boost library, but it still platform independent. You could implement the same without STL or boost if it is required.
以下示例使用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;
}
#2
Would depend on the OS, are we using windows or something POSIX compliant here?
将取决于操作系统,我们在这里使用Windows或POSIX兼容吗?