Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 509
Kornelije Petak Avatar asked May 24 '12 09:05

Kornelije Petak


Video Answer


2 Answers

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.

like image 124
CodesInChaos Avatar answered Sep 18 '22 14:09

CodesInChaos


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);
like image 42
João Angelo Avatar answered Sep 16 '22 14:09

João Angelo