Domanda

Can anyone please suggest/provide C++ code to generate random date (more precisely date & time or YYYY-MM-DDTHH:MM:SS), between today and say 5 years back. Should be fine if it is based on uniform distribution.

È stato utile?

Soluzione

Well, some would probably argue that the following is "more C than C++", but you can still give it a try...


First, define the maximum number of seconds that you want to "go back to":

#define MAX_NUM_OF_SECONDS (5*365*24*60*60) // number of seconds in 5 years

In order to ensure uniform distribution, this number should not be larger than RAND_MAX*RAND_MAX.


Then, implement a function that returns a Time/Date structure with random contents:

struct tm* GetTimeAndDate()
{
    unsigned int now_seconds  = (unsigned int)time(NULL);
    unsigned int rand_seconds = (rand()*rand())%(MAX_NUM_OF_SECONDS+1);
    time_t       rand_time    = (time_t)(now_seconds-rand_seconds);
    return localtime(&rand_time);
}

If you're working on a multi-threaded application, then please note that this function is not thread safe.


Finally, seed the RNG before you start using it (e.g, at the beginning of your program):

int main()
{
    ...
    srand((unsigned int)time(NULL));
    ...
}

Altri suggerimenti

If you know your begin date and end date, you can, using strptime(), convert those dates to time_t which are usually long integers. Given those long integers, you should be able to then create a random integer between them. Convert that long integer back to a date/time string using strftime().

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top