原理其實非常簡單,取出兩個時間差的秒數,再在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>
///www.bianceng.cn
/// </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);
}
}
}