Chr*_*isF 37
您可以尝试使用:
TimeSpan timeSpan = endDate - startDate;
var randomTest = new Random();
TimeSpan newSpan = new TimeSpan(0, randomTest.Next(0, (int)timeSpan.TotalMinutes), 0);
DateTime newDate = startDate + newSpan;
Run Code Online (Sandbox Code Playgroud)
这将为您提供不同的时间.如果你想要100(或任何超过1的东西)DateTimes,那么只需创建Random一次对象.在MSDN页面上Random详细解释了为什么创建几个Random对象临门是一个坏主意.
使用不同的TimeSpan构造函数将为您提供不同的粒度.从TimeSpan构造函数MSDN:
TimeSpan(Int64)将新TimeSpan初始化为指定的刻度数.
TimeSpan(Int32,Int32,Int32)将新TimeSpan初始化为指定的小时数,分钟数和秒数.
TimeSpan(Int32,Int32,Int32,Int32)将新TimeSpan初始化为指定的天数,小时数,分钟数和秒数.
TimeSpan(Int32,Int32,Int32,Int32,Int32)将新TimeSpan初始化为指定的天数,小时数,分钟数,秒数和毫秒数.
这是我的算法和代码:
在他们之间创建一个新的日期。只需将该随机数作为分钟添加到开始日期时间。
Random randNum = new Random();
DateTime minDt = new DateTime(2000,1,1,10,0,0);
DateTime maxDt = new DateTime(2000,1,1,17,0,0);
List<DateTime> myDates = new List<DateTime>();
//Random.Next in .NET is non-inclusive to the upper bound (@NickLarsen)
int minutesDiff = Convert.ToInt32(maxDt.Subtract(minDt).TotalMinutes+1);
for (int i = 0; i < 100; i++)
{
// some random number that's no larger than minutesDiff, no smaller than 1
int r= randNum.Next(1, minutesDiff);
myDates.Add(minDt.AddMinutes(r));
}
foreach (DateTime d in myDates)
{
Console.WriteLine(string.Format("{0:dd-MMM-yyyy hh:mm}",d));
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
16084 次 |
| 最近记录: |