Reputation: 7074
I need to add DateTimeOffset to a binary serialization library that I maintain. With DateTime I am simply saving the ticks as an Int64 but the DateTimeOffset does not have ticks as a constructor. How can it be re-constructed properly?
Example
DateTime date = new DateTime.Now;
long ticks = date.Ticks;
DateTime date2 = new DateTime(ticks);
DateTimeOffset dateOffset = new DateTimeOffset.Now;
long ticks2 = dateOffset.Ticks;
DateTimeOffset dateOffset2 = new DateTimeOffset(?)
Upvotes: 4
Views: 5527
Reputation: 4570
DateTimeOffset does not have ticks as a constructor
It does have a constructor that takes ticks plus an offset …
DateTimeOffset(Int64, TimeSpan)
… and TimeSpan can be constructed from a ticks value …
TimeSpan(Int64)
… so, you can serialize a DateTimeOffset
to two Int64
values …
DateTimeOffset dto = DateTimeOffset.Now;
var ticks = dto.Ticks;
var offset = dto.Offset.Ticks;
DateTimeOffset newDto = new DateTimeOffset(ticks, new TimeSpan(offset));
Debug.Assert(dto.EqualsExact(newDto), "DateTmeOffset Mismatch");
Upvotes: 4