Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

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?

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.

You might also like