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(?)
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");
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