基于给出错误值的Ticks构造DatetimeOffset对象

时间:2019-01-22 10:39:16

标签: c# datetimeoffset

我的 DatetimeOffset 值存储在数据库表中,如下所示:

2002-08-27 07:49:20.3190000 -11:00

现在这就是我如何在binary file中写入此值的方法:

DateTimeOffset d = "2002-08-27 07:49:20.3190000 -11:00";
BinaryWriter w ;
w.Write(d.Ticks);

现在,当我尝试使用二进制读取器读取此值时,它会像下面基于Ticks那样错误地生成:

BinaryReader r;
var dateTime = DateTime.FromBinary(r.ReadInt64());
return new DateTimeOffset(dateTime);

输出: 8/27/2002 7:49:20 AM +05:30

这是怎么回事?

如何基于Ticks正确构造确切的DatetimeOffset对象?

1 个答案:

答案 0 :(得分:1)

您需要同时存储UTC滴答和时区偏移量:

DateTimeOffset d = "2002-08-27 07:49:20.3190000 -11:00";
BinaryWriter w;
w.Write(d.Ticks);
w.Write(d.Offset.Ticks);

BinaryReader r;
var dateTime = new DateTime(r.ReadInt64());
var offset = new TimeSpan(r.ReadInt64());
return new DateTimeOffset(dateTime, offset);