简体   繁体   English

将DateTimeOffset转换为Int64并返回到DateTimeOffset

[英]Convert DateTimeOffset to Int64 and back to DateTimeOffset

I need to add DateTimeOffset to a binary serialization library that I maintain. 我需要将DateTimeOffset添加到我维护的二进制序列化库中。 With DateTime I am simply saving the ticks as an Int64 but the DateTimeOffset does not have ticks as a constructor. 使用DateTime,我只是将刻度保存为Int64,但DateTimeOffset没有将刻度作为构造函数。 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 DateTimeOffset没有刻度作为构造函数

It does have a constructor that takes ticks plus an offset 它确实有一个构造函数,它需要加上刻度线和偏移量 ……

DateTimeOffset(Int64, TimeSpan)

… and TimeSpan can be constructed from a ticks value …和TimeSpan可以通过刻度值构造…

TimeSpan(Int64) 

… so, you can serialize a DateTimeOffset to two Int64 values … …因此,您可以将DateTimeOffset序列化为两个 Int64值…

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM