范围之间的随机日期时间 - 不统一输出 [英] Random DateTime between range - not unified output
本文介绍了范围之间的随机日期时间 - 不统一输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我实现了以下RandomDate,但我总是不断收到价值封闭,从的日期,我可能会错过一些东西在这里....
公共静态的DateTime GetRandomDate(从日期时间,日期时间到)
{
VAR范围=新的时间跨度(to.Ticks - from.Ticks); VAR RND =新的随机(); VAR randTimeSpan =新的时间跨度((长)(range.TotalSeconds - rnd.Next(0,(INT)range.TotalSeconds))); 从+ randTimeSpan返回;
}
解决方案
您可以更改为:
静态只读随机RND =新的随机();
公共静态的DateTime GetRandomDate(从日期时间,日期时间到)
{
VAR范围=到 - 从; VAR randTimeSpan =新的时间跨度((长)(rnd.NextDouble()* range.Ticks)); 从+ randTimeSpan返回;
}
说明:我用 NextDouble()
,因为它使之间的一个数 0.0
和 1.0
。您的返回值将不会在我的解决方案的整体秒数。我搬到 RND
到现场的类/结构。因为这是最好的重用有一个随机
实例,而不是创建一个新的每一个时间只需要一个额外的随机数。
I implemented the below RandomDate, but I always keep getting values closed to "From" date, i probably miss something here....
public static DateTime GetRandomDate(DateTime from, DateTime to)
{
var range = new TimeSpan(to.Ticks - from.Ticks);
var rnd = new Random();
var randTimeSpan = new TimeSpan((long)(range.TotalSeconds - rnd.Next(0, (int)range.TotalSeconds)));
return from + randTimeSpan;
}
解决方案
You could change to:
static readonly Random rnd = new Random();
public static DateTime GetRandomDate(DateTime from, DateTime to)
{
var range = to - from;
var randTimeSpan = new TimeSpan((long)(rnd.NextDouble() * range.Ticks));
return from + randTimeSpan;
}
Explanation: I used NextDouble()
because it gives a number between 0.0
and 1.0
. Your return value won't be a whole number of seconds in my solution. And I moved rnd
out to a field on the class/struct. Because it's best to reuse one Random
instance, and not create a new one every time one needs just one additional random number.
这篇关于范围之间的随机日期时间 - 不统一输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文