Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a random date

I wrote this code snippet to generate random dates:

std::time_t curr_time = time(0);
std::time_t ten_years = 365 * 12 * 30 * 24 * 60;
std::time_t rand_date = curr_time - std::rand() % ten_years;
tm *ltm = std::localtime(&rand_date);
std::cout << ltm->tm_year + 1900 << " " << ltm->tm_mon + 1 << " " << ltm->tm_mday << std::endl;

However it always gives me the current date. What am i doing wrong?

like image 303
WonderCsabo Avatar asked Jan 25 '26 06:01

WonderCsabo


1 Answers

std::rand() may return rather small values, 0..32767 is the minimum range, and does so on some popular 32-bit platforms (MSVC among them). With time_t in seconds this only gives you about eight hours of random noise.

Try combining the results from a pair of std::rand calls instead. E.g. (std::time_t) std::rand() * RAND_MAX + std::rand() or switch to a better random number generator.

like image 175
doynax Avatar answered Jan 28 '26 00:01

doynax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!