2017-07-10 16 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