I'm trying to randomize the value for a simple DateTime
data field.
I wish to get a random date/time between two date/times (e.g. min date/time and max date/time).
So lets imagine I'm after a random date/time between
1/1/2000 10:00:00am
and 1/1/2000 5:00:00pm
.
Also, this code will be used in a for loop, with 100 items ... meaning all 100 items will have random date/times between the min/max date/time period.
Any ideas?
Really quickly:
Here's my algorithm and code:
create a new date between them. Simply add that random number as minutes to the start datetime.
Here's a method using a random number of ticks:
This method is exclusive the last date and inclusive the first. You can easily include the last date by adding one tick to the basic
(endDate - startDate).Ticks
quantity.This is what I'm using:
I used the approach in the accepted answer but modified it slightly as I had issues with it.
First, figure out what the precision is that you want on random DateTime (hours,minutes,seconds,ms,etc).
Then figure out the difference between the two dates in that unit.
Create a random integer between 0 and that difference.
Add the random integer in units to the original date.
Given the use case you stated above, calculate the difference outside in the for loop.
Inside the for loop, get the random int and construct the random date.
A one-liner based on ChrisF's solution