问题描述
我在控制台应用程序中运行以下代码:
让我们假设你的第一个 DateTime.Now (这是 dt1 )生成 00:00:00.00000 。第二个 DateTime.Now 生成 00:00:00.00002 (这些是理论值)和你的 dt2 将为 23:59:59.002 。
code>小时,分钟和第二个值;
dt1.Hour = 0;
dt2.Hour = 23;
dt1.Minute = 0;
dt2.Minute = 59;
dt1.Second = 0;
dt2.Second = 59;
结果 dt1.Hour * 3600 - dt2.Hour * 3600 + dt1.Minute * 60 - dt2.Minute * 60 + dt1.Second - dt2.Second)将为 -86399 不 1 。
I run below code in a console application:
while (true) { DateTime dt1 = DateTime.Now; DateTime dt2 = DateTime.Now.AddSeconds(-1); if ((dt1 - dt2).Seconds != 1) Console.Write((dt1 - dt2).Seconds.ToString()); }And I thought (dt1 - dt2).Seconds is always 1 but as I saw it write many 0 in the output !!??
Why does (dt1 - dt2).Seconds become 0 ?
Then I try below code:
if ((dt1.Hour * 3600 - dt2.Hour * 3600 + dt1.Minute * 60 - dt2.Minute * 60 + dt1.Second - dt2.Second) != 1) Console.Write((dt1.Second - dt2.Second).ToString());And this new code say may (dt1.Hour * 3600 - dt2.Hour * 3600 + dt1.Minute * 60 - dt2.Minute * 60 + dt1.Second - dt2.Second) is always 1 (However I know in 23:59:59 => 00:00:00 it should write a value)
解决方案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);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.
这篇关于“DateTime.Now - DateTimeNow.AddSecond(-1)”可以为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!