tags:

views:

99

answers:

4

I have two dates as strings (dd-mm-yyyy). How can i get a random date between these two dates?

+3  A: 

You can convert the dates to Unix timestamp. Randomly pick a timestamp between the two timestamps and convert it back to date.

codaddict
... and strip the time part.
Joey
how i convert date to unix timestamp?
amitlicht
Take a look at the function strptime
Sjoerd
A: 

Transform the dates into 3 ints: d1 = dd, m1 = mm, y1 = yyyy, same with d2, m2, y2

Then, assuming you know how to generate random numbers ( http://www.cprogramming.com/tutorial/random.html ), generate a random number between y1 and y2, which will act as the year. Then dd can be generated random between 1 and 28, and mm between 1 and 12. This will limit all of your days to max 28 though. You can generate the month randomly first, then use a table to find out how many days are in each month (if you think about it you don't even need a table, just a way to detect leap years to account for february having 29 days).

To generate a random int between a and b, you can use:

int random = a + rand() % (b - a + 1);

You can extend this to work for dates where y1 = y2 and even m1 = m2 as well with just a few extra conditions

IVlad
+1  A: 

Convert the dates to fixed numbers such as a Julian value (call them J1 and J2). Generate a "random" number from 0 <= N <= J2-j1. Then convert J1+N from Julian back to a date.

Mark Wilkins
A: 

Use the types and functions from the standard library time.h:

http://en.wikipedia.org/wiki/Time.h

Convert the string parts to ints, then convert these to time_t. After calculating your random value in between, go the other way to get your result in a string.

Secure