Random Time Generator for time betweeen 7AM to 11AM
Solution 1
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.
Solution 2
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");
Solution 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
.
Solution 4
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.
Cocoa Dev
Updated on January 15, 2020Comments
-
Cocoa Dev over 4 years
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.
-
kaveman over 11 yearspick a random number h [7,11]. If h < 11, pick another random number m [0,59], else m is 0
-
-
kaveman over 11 yearsNote this solution has the possibility of picking times > 11:00am, e.g. 11:15am
-
kaveman over 11 yearsbut now 11:00am is not possible...
-
Cocoa Dev over 11 yearshow do I use t like get the time?