11

I am creating a test file and I need to fill it with random times between 7AM to 11AM. Repeating entries are OK as long as they aren't all the same

I'm also only interested in HH:MM (no seconds)

I don't know where to start. I did Google before posting and I found an interesting search result

www.random.org/clock-times/

Only issue is that all times "randomly" generated are in sequential order. I can put it out of sequence once but I need to generate 100 to 10,000 entries.

I am hoping to create a WinForm C# app that will help me do this.

potashin
  • 44,205
  • 11
  • 83
  • 107
Cocoa Dev
  • 9,361
  • 31
  • 109
  • 177
  • pick a random number **h** [7,11]. If **h** < 11, pick another random number **m** [0,59], else **m** is 0 – kaveman Nov 27 '12 at 18:17

9 Answers9

18

Calculate the number of minutes between your start and stop times then generate a random number between 0 and the maximum number of minutes:

Random random = new Random();
TimeSpan start = TimeSpan.FromHours(7);
TimeSpan end = TimeSpan.FromHours(11);
int maxMinutes = (int)((end - start).TotalMinutes);

for (int i = 0; i < 100; ++i) {
   int minutes = random.Next(maxMinutes);
   TimeSpan t = start.Add(TimeSpan.FromMinutes(minutes));
   // Do something with t...
}

Notes:

  • You should only create one random object, otherwise you will get many duplicates in a row.
  • The start time is inclusive but the end time is exclusive. If you want to include the end time too, add 1 to maxMinutes.
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
12

Create a DateTime value for the lower bound, and a random generator:

DateTime start = DateTime.Today.AddHours(7);
Random rnd = new Random();

Now you can create random times by adding minutes to it:

DateTime value = start.AddMinutes(rnd.Next(241));

To format it as HH:MM you can use a custom format:

string time = value.ToString("HH:mm");
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
3

Here is a generic method to give you a random date between a given start and end date.

public static DateTime RandomDate(Random generator, DateTime rangeStart, DateTime rangeEnd)
{
    TimeSpan span = rangeEnd - rangeStart;

    int randomMinutes = generator.Next(0, (int)span.TotalMinutes);
    return rangeStart + TimeSpan.FromMinutes(randomMinutes);
}

If you use something like this a lot you could make it an extension method on Random.

Servy
  • 202,030
  • 26
  • 332
  • 449
2

Create a Random object and use that to create a new DateTime

Random rand = new Random();
//Note that Random.Next(int, int) is inclusive lower bound, exclusive upper bound
DateTime myDateTime = new DateTime(2012, 11, 27, 
    rand.Next(7, 11), rand.Next(0, 60), 0);

Then use the time output where you want it.

Dave Zych
  • 21,581
  • 7
  • 51
  • 66
0
List<DateTime> randomTimes = new List<DateTime>();
Random r = new Random();
DateTime d = new DateTime(2012, 11, 27, 7, 0, 0);

for (int i = 0; i < 100; i++)
{
    TimeSpan t = TimeSpan.FromSeconds(r.Next(0, 14400));
    randomTimes.Add(d.Add(t));
}

randomTimes.Sort();

The number 14400 is the number of seconds between 7 AM and 11 AM, which is used as the basis for random number generation.

The randomTimes list can be used with DateTime formatting to achieve the desired output format, like:

Console.WriteLine("HH:mm", randomTimes[0]);
JYelton
  • 35,664
  • 27
  • 132
  • 191
0
var random = new Random();
var startDateTime = new DateTime(2000, 1, 1, 7, 0, 0, 0);
var maxDuration = TimeSpan.FromHours(4);

var values = Enumerable.Range(0, 100)
    .Select(x => {
        var duration = random.Next(0, (int)maxDuration.TotalMinutes);
        return startDateTime.AddMinutes(duration).ToString("HH:mm");
    })
    .ToList();

values = values.Distinct().ToList();

Console.WriteLine("{0} values found. Min: {1}, Max: {2}", values.Count, values.Min(), values.Max());

Throwing my hat in the ring :)

Edit: It's slightly embarrassing to see so many answers for effectively is a dead simple question. Anyway, nice to see different styles. Reading the question I was surprised to see the OP ask to create Win Forms app to do this. The task seemed so straight forward, I wanted to write the solution in LinqPad!

Amith George
  • 5,806
  • 2
  • 35
  • 53
0

A simple option (picking the hour and minute as random ints):

Random r = new Random();

//pick the hour
int h = r.Next(7,12);

//pick the minute
int m = 0;
if(h < 11)
    m = r.Next(0,60);

//compose the DateTime
DateTime randomDT = new DateTime(year, month, day, h, m, 0);
kaveman
  • 4,339
  • 25
  • 44
0

Something like this:

private static Random rng = new Random();
public IEnumerable<DateTime> RandomDateTimes( DateTime lowerBound , DateTime upperBound , int count )
{
    TimeSpan period = upperBound - lowerBound ;

    if ( period <= TimeSpan.Zero || period > new TimeSpan(1,0,0,0) ) throw new ArgumentException();
    if ( count < 0 ) throw new ArgumentException() ;

    int rangeInMinutes = (int) period.TotalMinutes ; // period is 0 through 1440

    for ( int i = 0 ; i < count ; ++i )
    {
        int offset = rng.Next(rangeInMinutes) ;
        yield return lowerBound.AddMinutes(offset) ;
    }
}
public IEnumerable<DateTime> OrderedRandomDateTimes( DateTime lowerbound , DateTime upperBound , int count )
{
    yield return RandomDateTimes( lowerbound , upperBound , count ).OrderBy( x = x ) ;
}
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
0

Maybe I am missing something but isn't it as simple as this...

Random rand = new Random();

// Range can be any number from 100 to 10000
Enumerable.Range(1, 10000).Select(v => TimeSpan.FromMinutes(rand.Next(420, 661)))

If you wanted to make it simplier to understand the numbers you could expand it out....

Random rand = new Random();
int startTime = Convert.ToInt32(TimeSpan.FromHours(7).TotalMinutes);
int endTime = Convert.ToInt32(TimeSpan.FromHours(11).TotalMinutes) + 1;     // To make 11:00 inclusive

Enumerable.Range(1, 10000).Select(v => TimeSpan.FromMinutes(rand.Next(startTime, endTime))).Dump();
Gene S
  • 2,735
  • 3
  • 25
  • 35