Why DateTime.Now.ToBinary () returns a different value than when created by the constructor

Here is what I 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 conclusion:

-8588637543837682554 634734565017110000

timeAand timeBshould be essentially the same, but they will be converted to a completely different (negative) binary.

Why is this happening? Why does a direct call ToBinary()on DateTime.Nowgive different results?

EDIT . Since my problem was misunderstood (and thus it was omitted), I corrected my post to better present the real question. The problem was DateTime.Kind, and it was a real problem, not a slight difference in two consecutive DateTime.Now calls.

+3
source share
5 answers

DateTime, .

DateTime, DateTime.Now , .

var now = DateTime.Now;
long timeA = now.ToBinary();
long timeB = new DateTime(now.Ticks, now.Kind).ToBinary();;

Console.WriteLine(timeA);
Console.WriteLine(timeB);
+6

Kind, ToBinary.

DateTime.Now Kind == DateTimeKind.Local, DateTime, new DateTime(...), Kind == DateTimeKind.Unspecified. new DateTime(...), .

+9

DateTime.FromBinary() DateTime.

oroginal , . MSDN, .

+2

Ok, first two DateTimes have different Kind. DateTime.Nowlooks like Local, the second is Kind Unspecified.

var now = DateTime.Now;
var timeA = now.ToBinary();
var dateB = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, now.Millisecond, now.Kind);
var timeB = dateB.ToBinary();
Console.WriteLine(timeA);
Console.WriteLine(timeB);

This leads to different results:

-8588637530157241842
-8588637530157245808

Using ticks gives the correct results, but this is due to the fact that ticks use 100 nanosecond intervals, which are even more accurate than milliseconds.

Milliseconds are the smallest you can specify, but not the smallest internal variable.

var dateB = new DateTime(now.Ticks, now.Kind);
+2
source

Between two calls to DateTime.Now, miliseconds pass, they make the two values ​​different

0
source

All Articles