2017-07-10 17 views
1

我有一個函數可以在兩個日期之間的範圍內生成隨機日期時間...並以某種方式使隨機日期在最小日期之前。我的代碼有什麼問題?爲什麼我的隨機DateTime生成器使日期超出範圍?

public void TestFunct() 
{ 
    GenerateRandomTimeBetweenDates(new Random(), DateTime.ParseExact("01.01.2017 00:00:00", "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture), DateTime.ParseExact("01.02.2017 00:00:00", "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture)); 
} 

public DateTime GenerateRandomTimeBetweenDates(Random RNG, DateTime dt1, DateTime dt2) 
{ 
    int dt1_sec = (int)dt1.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; //calc seconds since Unix epoch 
    int dt2_sec = (int)dt2.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; 
    int random_sec = RNG.Next(Math.Min(dt1_sec, dt2_sec), Math.Max(dt1_sec, dt2_sec)); //RNG is Random instance. Here I generate seconds amount between two amounts - minimal and maximal. 

    DateTime random_dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(random_sec); //I try to recreate date by adding generated seconds amount to Unix epoch. 

    if (random_dt.Year == 2016) 
     random_dt = random_dt; //this I use to trigger breakpoint 

    return random_dt; 
} 

enter image description here

+0

1)不要忘記檢查'if(dt1> dt2)'? 2)'DateTime random_dt = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc).AddSeconds(random_sec).AddSeconds(dt1_sec);' – KamikyIT

+0

'BuyersManager.RNG.Next'中會發生什麼? ? – krillgar

+0

@krillgar - 抱歉,忘記指出這只是正常的隨機實例。 – Kosmos

回答

2

這裏的問題是ToUniversalTime()。如果您的日期有LocalUnspecifiedUnspecified - ToUniversalTime會將它們轉換爲UTC假設(在Unspecified的情況下)它們是本地的。通過這樣做,您的dt1即2017年1月1日將以UTC表示2016年的日期。當隨機值接近最小值時 - 結果也將在2016年。要解決 - 只需刪除致電ToUniversalTime()。你可以只是將其刪除,因爲,Substract方法的文檔:

的System.DateTime.Subtract(System.DateTime的)方法不 考慮兩個 的System.DateTime.Kind屬性的值

然而要注意最好是用同一種作爲輸入,返回結果進行System.DateTime的值時,減法,所以:

DateTime random_dt = new DateTime(1970, 1, 1, 0, 0, 0, dt1.Kind).AddSeconds(random_sec); 

因爲Ø如果你的輸入代表本地時間,並且結果是以UTC計算的話,那麼無論如何 - 沒有多大意義。

+0

謝謝。我按你所說的做了,而且沒有更多的外人給我。 – Kosmos