开发者

Hot to get random date in range

开发者 https://www.devze.com 2022-12-21 16:18 出处:网络
I have two dates as strings (dd-mm-yyyy). How can i get a random date 开发者_开发百科between these two dates?You can convert the dates to Unix timestamp. Randomly pick a timestamp between the two time

I have two dates as strings (dd-mm-yyyy). How can i get a random date 开发者_开发百科between these two dates?


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


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消