2

I am automating an application where records can be opened between specified date ranges. I know that I can create an array that randomly picks a number in my array, such as:

DateTime.Now.AddDays(90).ToString("MM/dd/yyyy")

However, I would like to know if there is a better way to go about this. Please help! Thanks.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
user2917239
  • 898
  • 3
  • 12
  • 27

2 Answers2

14
void Main()
{   
    Console.WriteLine(DateTime.UtcNow.AddDays(new Random().Next(90)));
}

This will add a random amount of days to the start date, essentially ending up with a random date.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
1

Assuming that you want the dates to be in the range of 90 days of the date of generation. Then, you can try this:

int seed = (int)DateTime.Now.Ticks;
int days = seed % 90;
DateTime.Now.AddDays(days).ToString("MM/dd/yyyy");

You can, of course, refactor this. I was verbose for the sake of clarity. You can also change the integer value of 90 to any integer you want to be the upper-bound of your range.

Hope this helps.

Josh Wheelock
  • 369
  • 4
  • 9
  • I suggest against using Ticks for random number generation. At most, they should be the seed for the real random number generator. The tick count may not be sufficiently "smooth" and may be distinctly non-random when used repeatedly. Jeroen's solution above is better, as new Random() uses tickcount as the seed by default. – Brendan Hill Nov 18 '13 at 22:31
  • Really? A down vote? Why not just up vote the answer you like? (He entered it the same time I entered mine - btw) My answer is correct and works. A Random object has the same limitations as using Ticks. The problem with ticks is that Windows does not update the value at a very small interval. Therefore, if called multiple times within a short interval you could end up using the same seed. Using the Random class is similar within an interval of ~16ms. Therefore, I don't care which one you use, but your down vote is unwarranted. – Josh Wheelock Nov 18 '13 at 22:47
  • 2
    I did not downvote but I can see the reasoning behind it. Your solution is not random at all and like you said can generate duplicate values if called in a tight loop. If you use `Random` [correctly](http://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number/768001#768001) (by putting it outside of the method body as either a class local or a static variable) you can call it as fast as you want and get random values every time. – Scott Chamberlain Nov 18 '13 at 22:53
  • Nothing personal, but your solution is not random at all. If it was used in a testing harness or something critical then it would not serve its function. A Random() object does not suffer from this limitation since it will generate sufficient randomness for requests repeated in quick succession. – Brendan Hill Nov 18 '13 at 22:56