Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DateTimeOffset to Int64 and back to DateTimeOffset

Tags:

c#

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(?)
like image 622
Greg Finzer Avatar asked Oct 14 '25 09:10

Greg Finzer


1 Answers

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");
like image 97
Frank Boyne Avatar answered Oct 16 '25 22:10

Frank Boyne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!