我想知道是否有任何可能的方法来生成从现在到10天的范围内的随机posix :: time?
我想到了类似的东西:
using namespace boost::posix_time;
second_clock now = second_clock::local_time();
second_clock back = now - hours(240);
这样做我将在10天之后获得当地日期和日期,但是如何从该期间生成一些随机日期?我知道这可能很容易,但我没有想法; /
答案 0 :(得分:2)
我建议使用uniform_int_distribution并制作一个通用实用程序,可以为不同的时间窗口创建随机时间戳生成器:
Live on Coliru
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
#include <random>
using boost::posix_time::ptime;
using boost::posix_time::minutes;
using boost::posix_time::seconds;
using boost::posix_time::hours;
int main() {
auto rng = std::mt19937 { std::random_device{}() }; // correctly seeded random generator
auto date_selector = [&](boost::posix_time::time_duration window = boost::posix_time::hours(24*10), ptime now = boost::posix_time::second_clock::local_time()) {
auto start = now - window;
unsigned size = (now - start).total_seconds();
return [=]() mutable {
return start + seconds(std::uniform_int_distribution<unsigned>(0,size)(rng));
};
};
auto seven_days = date_selector(hours(7*24));
std::cout << "seven_days:\n";
for (auto i = 10; i; --i) std::cout << "\t" << seven_days() << "\n";
auto ten_minutes = date_selector(minutes(10));
std::cout << "ten_minutes:\n";
for (auto i = 10; i; --i) std::cout << "\t" << ten_minutes() << "\n";
}
打印,例如
seven_days:
2016-Dec-27 22:32:13
2016-Dec-30 10:02:14
2016-Dec-27 13:14:59
2016-Dec-29 22:44:16
2016-Dec-30 17:28:37
2016-Dec-31 05:21:38
2017-Jan-01 10:33:44
2017-Jan-01 06:50:51
2016-Dec-28 09:52:12
2016-Dec-29 12:35:50
ten_minutes:
2017-Jan-02 13:34:52
2017-Jan-02 13:38:25
2017-Jan-02 13:34:19
2017-Jan-02 13:37:44
2017-Jan-02 13:38:51
2017-Jan-02 13:39:34
2017-Jan-02 13:41:18
2017-Jan-02 13:41:05
2017-Jan-02 13:35:32
2017-Jan-02 13:37:08
答案 1 :(得分:-1)
如果我理解正确,你想在今天和10天之间获得一个随机时间戳。
我建议你用毫秒计算10天,然后在该范围内选择一个随机数,并将其减去现在的时间戳。
遗憾的是,rand无法生成一个大的随机数。 因此,您可以在部分中创建此类时间戳,并从中减去当前时间戳。 unsigned int days_in_milli, hrs_in_milli, mins_in_milli, secs_in_milli, num_milli_back;
srand(time(NULL));
num_milli_back = rand() % 1000;
days_in_milli = (rand() % 10) * 86400000;
hrs_in_milli = (rand() % 24) * 3600000;
mins_in_milli = (rand() % 60) * 60000;
secs_in_milli = (rand() % 60) * 1000;
cout << ((unsigned)time(NULL) - (days_in_milli + hrs_in_milli + mins_in_milli + secs_in_milli + num_milli_back)) << endl;
希望这很有帮助