This is what I've tried:
DateTime now = DateTime.Now;
long timeA = now.ToBinary();
long timeB = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, now.Millisecond).ToBinary();
Debug.WriteLine("{0} {1}", timeA, timeB);
This is the output:
-8588637543837682554 634734565017110000
The timeA
and timeB
should essentially be the same thing, but they are converted to a totally different (negative) binary.
Why does this happen? Why does directly calling ToBinary()
on DateTime.Now
produce different results?
EDIT: Since my issue was misunderstood (and thus downvoted) I have corrected my post to better represent the real question. The problem was in DateTime.Kind and that was the real issue, not the small difference in two consecutive DateTime.Now calls.
Your two values have a different Kind
, and the kind gets also serialized by ToBinary
.
DateTime.Now
has Kind == DateTimeKind.Local
, the DateTime you create with new DateTime(...)
has Kind == DateTimeKind.Unspecified
. You can use another overload for new DateTime(...)
if you want a different kind.
They are not the same DateTime
values so this is expected.
To work on the same value of DateTime
you need to call the DateTime.Now
just once and then reuse it.
var now = DateTime.Now;
long timeA = now.ToBinary();
long timeB = new DateTime(now.Ticks, now.Kind).ToBinary();;
Console.WriteLine(timeA);
Console.WriteLine(timeB);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With