Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following code:

var a = (DateTime.Now.Subtract(DateTime.Now.AddTicks(8))).Ticks;
var b = (DateTime.Now - DateTime.Now.AddTicks(8)).Ticks;

When I check the values I see that:

a = -78
b = -20

How come? Shouldn't both be -8?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
226 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are depending on the system to do everything at the same time, which it cannot. Each time you get DateTime.Now, it has a different value.

A quick experiment reveals that capturing the value of DateTime.Now in the beginning, and then performing operations on that:

var d = DateTime.Now;
var a = (d.Subtract(d.AddTicks(8))).Ticks;
var b = (d - d.AddTicks(8)).Ticks;

Yields the result you were expecting. a and b have the same value, -8.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...