Random Time Generator for time betweeen 7AM to 11A

2020-06-20 02:55发布

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.

9条回答
冷血范
2楼-- · 2020-06-20 03:47
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]);
查看更多
放我归山
3楼-- · 2020-06-20 03:50

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);
查看更多
迷人小祖宗
4楼-- · 2020-06-20 03:51

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");
查看更多
登录 后发表回答