What's the best practice for getting a random

2020-05-25 08:04发布

I'm trying to randomize the value for a simple DateTime data field.

I wish to get a random date/time between two date/times (e.g. min date/time and max date/time).

So lets imagine I'm after a random date/time between

1/1/2000 10:00:00am and 1/1/2000 5:00:00pm.

Also, this code will be used in a for loop, with 100 items ... meaning all 100 items will have random date/times between the min/max date/time period.

Any ideas?

7条回答
不美不萌又怎样
2楼-- · 2020-05-25 08:26

You could try using:

var randomTest = new Random();

TimeSpan timeSpan = endDate - startDate;
TimeSpan newSpan = new TimeSpan(0, randomTest.Next(0, (int)timeSpan.TotalMinutes), 0);
DateTime newDate = startDate + newSpan;

This will give you different times down to the minute. If you want 100 (or any thing more than 1) DateTimes then only create the Random object once. The MSDN page on Random explains in detail why creating several Random objects in quick succession is a bad idea.

Using a different TimeSpan constructor will give you different granularity. From the TimeSpan constructor MSDN:

TimeSpan(Int64) Initializes a new TimeSpan to the specified number of ticks.
TimeSpan(Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of hours, minutes, and seconds.
TimeSpan(Int32, Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of days, hours, minutes, and seconds.
TimeSpan(Int32, Int32, Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of days, hours, minutes, seconds, and milliseconds.

查看更多
登录 后发表回答