-5

I have a listener which needs to be active randomly for 10 time for say 20 min in a given time period. So if the time period is say from 2013/08/20 10:00 to 2013/08/20 22:00, I need to generate a random DateTime 10 times between this range keeping in mind that the listener needs a time of 20 min.

furkick
  • 423
  • 6
  • 18
user2697452
  • 352
  • 1
  • 5
  • 14

2 Answers2

1

You can use the Ticks property on DateTime to find the difference between the two and then generate a random number of ticks in that range:

Random r = new Random();
int randTicks = r.Next(0, (int) (dt2.Ticks - dt1.Ticks));

Now you can add that random # of ticks to make a random DateTime between dt1 and dt2:

DateTime dtRand = dt1.AddTicks(randTicks);
tnw
  • 13,521
  • 15
  • 70
  • 111
  • Simple and effective, you may need to convert the difference of two ticks to an int first though, as Next method doesn't take long type. – liang Jul 07 '15 at 15:35
  • @liang Thanks, you're correct. Updated. – tnw Jul 07 '15 at 15:54
  • 1
    Unfortunately, this doesn't work as i test it, casting long to int directly will cause overflow. – liang Jul 07 '15 at 16:23
  • @liang I suppose if the difference between the dates is large enough this would be the case. If so, I'd recommend a more robust solution which individually randomizes each element of a DateTime based on what kind of precision you need (just a date, or both a date and time, etc). The solution provided below by Karl may also work for you though that only works down to the minute and doesn't randomize the time any further. – tnw Jul 07 '15 at 16:30
  • i still prefer the simpleness of your approach, a further precision scale down may do the trick. – liang Jul 07 '15 at 16:36
1

This should get you started:

TimeSpan timeSpan = endDate - startDate;
var randomTest = new Random();

for(var i = 0; i < 10; i++)
{
    TimeSpan newSpan = new TimeSpan(0, randomTest.Next(0, (int)timeSpan.TotalMinutes), 0);
    DateTime newDate = startDate + newSpan;

    // Do something with newDate before you loop again
}

Note: You will need to provide the endDate and startDate values.

Alberto Solano
  • 7,972
  • 3
  • 38
  • 61
Karl Anderson
  • 34,606
  • 12
  • 65
  • 80