我想随机一个简单的DateTime数据字段的值。
I'm trying to randomize the value for a simple DateTime datafield.
我希望得到的两个日期/时间(例如分钟日期/时间和最大的日期/时间)随机的日期/时间。
I wish to get a random date/time between two date/times (e.g. min date/time and max date/time).
因此,让想象我在
1/1/2000上午10点至下午5点1/1/2000
1/1/2000 10am and 1/1/2000 5pm.
此外,该code将在一个for循环使用,100项..这意味着所有100个项目将有随机的日期/最小/最大日期/时间段之间的时间。
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.
唷!
什么想法?
您可以尝试使用:
TimeSpan timeSpan = endDate - startDate;
var randomTest = new Random();
TimeSpan newSpan = new TimeSpan(0, randomTest.Next(0, (int)timeSpan.TotalMinutes), 0);
DateTime newDate = startDate + newSpan;
这会给你下到分钟的时间不同。如果你想100(或任何事情超过1)的DateTime
取值则仅创建随机
对象一次。在随机的 MSDN页
详细解释了为什么创建快速连续几个随机
对象是个糟糕的主意。
This will give you different times down to the minute. If you want 100 (or any thing more than 1) DateTime
s 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.
使用不同的时间跨度
构造会给你不同的粒度。从时间跨度构造MSDN :
Using a different TimeSpan
constructor will give you different granularity. From the TimeSpan constructor MSDN:
时间跨度(Int64的)初始化新的入库时间蜱指定数量。 时间跨度(的Int32,的Int32,Int32)在初始化新的入库时间,以小时,分钟和秒指定的次数。 时间跨度(的Int32,的Int32,的Int32,Int32)在初始化新的入库时间到指定数量的 天,小时,分钟和秒。 时间跨度(的Int32,的Int32,的Int32,的Int32,Int32)在初始化新的入库时间,以日,时,分,秒和毫秒指定次数。
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.