原理其实非常简单,取出两个时间差的秒数,再在0到该秒数之间随机获取一个整数,将其做为秒添加到较小的时间上,可以说实现上并没什么技术难点,可以在数据类型的边界条件上却需要格外的注意,比如将大于 system.int32.maxvalue 或小于 system.int32.minvalue 的值转成 int 时,如果直接在变量前加上类型名转换((int)d),不会有有异常产生,但得到的值却是 system.int32.minvalue,还有就是对于math.abs 方法,当参数 value 等于 minvalue 将会引发 system.overflowexception 异常。
代码如下:
using system;
namespace yyw
{
public class datetimehelper
{
/**//// <summary>
/// 获取随机时间
/// <remarks>
/// 由于random 以当前系统时间做为种值,所以当快速运行多次该方法所得到的结果可能相同,
/// 这时,你应该在外部初始化 random 实例并调用 getrandomtime(datetime time1, datetime time2, random random)
/// </remarks>
/// </summary>
/// <param name="time1"></param>
/// <param name="time2"></param>
/// <returns></returns>
public static datetime getrandomtime(datetime time1, datetime time2)
{
random random = new random();
return getrandomtime(time1, time2, random);
}
/**//// <summary>
/// 获取随机时间
/// </summary>
/// <param name="time1"></param>
/// <param name="time2"></param>
/// <param name="random"></param>
/// <returns></returns>
public static datetime getrandomtime(datetime time1, datetime time2, random random)
{
datetime mintime = new datetime();
datetime maxtime = new datetime();
system.timespan ts = new system.timespan(time1.ticks - time2.ticks);
// 获取两个时间相隔的秒数
double dtotalsecontds = ts.totalseconds;
int itotalsecontds = 0;
if (dtotalsecontds > system.int32.maxvalue)
{
itotalsecontds = system.int32.maxvalue;
}
else if (dtotalsecontds < system.int32.minvalue)
{
itotalsecontds = system.int32.minvalue;
}
else
{
itotalsecontds = (int)dtotalsecontds;
}
if (itotalsecontds > 0)
{
mintime = time2;
maxtime = time1;
}
else if (itotalsecontds < 0)
{
mintime = time1;
maxtime = time2;
}
else
{
return time1;
}
int maxvalue = itotalsecontds;
if (itotalsecontds <= system.int32.minvalue)
maxvalue = system.int32.minvalue + 1;
int i = random.next(system.math.abs(maxvalue));
return mintime.addseconds(i);
}
}
}
测试代码:
using system;
using nunit.framework;
namespace yyw
{
[testfixture]
public class datetimehelperfixture
{
/**//// <summary>
/// 边界测试
/// </summary>
[test]
public void testgetrandomtime()
{
datetime mintime = datetime.minvalue;
datetime maxtime = datetime.maxvalue;
random random = new random();
for (int i = 0; i < 10000; i++)
{
datetime randomtime = datetimehelper.getrandomtime(maxtime, mintime, random);
checkresult(mintime, maxtime, randomtime);
}
for (int i = 0; i < 10000; i++)
{
datetime randomtime = datetimehelper.getrandomtime(mintime, maxtime, random);
checkresult(mintime, maxtime, randomtime);
}
}
private void checkresult(datetime mintime, datetime maxtime, datetime randomtime)
{
system.timespan ts1 = new system.timespan(randomtime.ticks - mintime.ticks);
system.timespan ts2 = new system.timespan(randomtime.ticks - maxtime.ticks);
assert.istrue(ts1.seconds >= 0 && ts2.seconds <= 0);
}
}
}
新闻热点
疑难解答