关于c#:根据Ticks给出不正确的值构造DatetimeOffset对象

Constructing DatetimeOffset object based on Ticks giving incorrect value

DateTimeOffset值要存储在数据库表:我as belowP></

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

现在这样的值:在binary filewrite thisP></

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

现在,当我试图使用二进制阅读器读取这个值,那么它是生成基于Ticks类:incorrectly belowP></

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

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

这是如何发生的?P></

how to construct DateTimeOffset对象基于ticks properly精确吗?P></


您需要同时存储UTC刻度和时区偏移量:

1
2
3
4
5
6
7
8
9
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);