How can `DateTime.Now - DateTimeNow.AddSecond(-1)` be zero

后端 未结 2 1832
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 10:04

I run below code in a console application:

while (true)
{
    DateTime dt1 = DateTime.Now;
    DateTime dt2 = DateTime.Now.AddSeconds(-1);

    if ((dt1 - dt2).S         


        
相关标签:
2条回答
  • 2021-01-25 10:22

    Because you evaluate your DateTime.Now value again for your dt2 variable, that's why this little difference is completely expected. That means your second DateTime.Now calculated at least 1 Tick and at most 10 million Ticks (which is equal to 1 second) after the first one.

    And since DateTime.Second property calculated with InternalTicks and TicksPerSecond, it returns zero when InternalTicks is less than TicksPerSecond value after calcualte remainder with 60.

    public int Second
    {
         get
         {
            return (int)((InternalTicks / TicksPerSecond) % 60); 
         }
    } 
    

    If you use same DateTime.Now value for both variable, that should be ok.

    DateTime now = DateTime.Now;
    DateTime dt1 = now;
    DateTime dt2 = now.AddSeconds(-1);
    

    Why (dt1.Hour * 3600 - dt2.Hour * 3600 + dt1.Minute * 60 - dt2.Minute * 60 + dt1.Second - dt2.Second) is always 1?

    Well, it is not always 1. Let's assume your first DateTime.Now (which is dt1) generates 00:00:00.00000. And second DateTime.Now generates 00:00:00.00002 (those are theoretical values) and your dt2 will be 23:59:59.002.

    Let's look at the Hours, Minute and Second values;

    dt1.Hour = 0;
    dt2.Hour = 23;
    dt1.Minute = 0;
    dt2.Minute = 59;
    dt1.Second = 0;
    dt2.Second = 59;
    

    And the result of dt1.Hour * 3600 - dt2.Hour * 3600 + dt1.Minute * 60 - dt2.Minute * 60 + dt1.Second - dt2.Second) will be -86399 not 1.

    0 讨论(0)
  • 2021-01-25 10:23

    Try doing this

     DateTime dt1 = DateTime.Now;
     DateTime dt2 = dt1.AddSeconds(-1);
    

    You have initialized 2 different timestamps (which vary by a tiny fraction of time), when you accessed the DateTime.Now.

    0 讨论(0)
提交回复
热议问题