C# DateTimeOffset:从LiteDb集合获取数据时,TZ偏移量重置为+00:00
插入时,偏移量正常,但检索文档时,偏移量将重置为+00:00 财产:C# DateTimeOffset:从LiteDb集合获取数据时,TZ偏移量重置为+00:00,c#,asp.net-mvc,asp.net-core,litedb,C#,Asp.net Mvc,Asp.net Core,Litedb,插入时,偏移量正常,但检索文档时,偏移量将重置为+00:00 财产: public DateTimeOffset CreatedOn { get; set; } 插入: user.CreatedOn = DateTimeOffset.Now; // 01/20/2021 6:05:21 PM +05:30 col.Insert(user); col.EnsureIndex(x => x.Username); 查找: user.CreatedOn变为 2021年1月20日下午6:05:2
public DateTimeOffset CreatedOn { get; set; }
插入:
user.CreatedOn = DateTimeOffset.Now; // 01/20/2021 6:05:21 PM +05:30
col.Insert(user);
col.EnsureIndex(x => x.Username);
查找:
user.CreatedOn变为
2021年1月20日下午6:05:21+00:00
我做错什么了吗?来自
按照BSON规范,日期时间值最多只能存储毫秒。所有日期时间值在存储时转换为UTC,在检索时转换回本地时间
看起来没有实际的DateTimeOffset支持。就我个人而言,我认为在检索时转换为当地时间是一个糟糕的想法,但这是一个稍微不同的问题。此外,鉴于0的偏移量不正确,它看起来没有真正正确地转换为本地时间
我建议避免在LiteDb中使用DateTimeOffset,直到它真正被支持维护偏移量。这是因为LiteDb使用value.UtcDateTime存储DateTimeOffset。这是不幸的,但由于兼容性,无法更改。但是,您可以通过创建自定义序列化程序来覆盖此行为:
BsonMapper.Global.RegisterType<DateTimeOffset>
(
serialize: obj =>
{
var doc = new BsonDocument();
doc["DateTime"] = obj.DateTime.Ticks;
doc["Offset"] = obj.Offset.Ticks;
return doc;
},
deserialize: doc => new DateTimeOffset(doc["DateTime"].AsInt64, new TimeSpan(doc["Offset"].AsInt64))
);
LiteDb完全支持DateTimeOffset吗?从外观上看,它似乎只支持UTC DateTime,即使它是使用偏移量存储的,从注释上看,维护人员似乎不想在任何时候添加支持,只要您可以转换,就可以将时间存储为长时间的时间戳。因此,在存储数据时存储DateTimeOffset.ToUnixTimeSeconds,在检索数据时存储DateTimeOffset.FromUnixTimeSeconds。@GlennSills:这肯定会避免DateTimeOffset中的误导信息,是的。如果OP实际上需要日期/时间和偏移量信息,那么看起来他们需要将偏移量存储在单独的数据库字段中。
BsonMapper.Global.RegisterType<DateTimeOffset>
(
serialize: obj =>
{
var doc = new BsonDocument();
doc["DateTime"] = obj.DateTime.Ticks;
doc["Offset"] = obj.Offset.Ticks;
return doc;
},
deserialize: doc => new DateTimeOffset(doc["DateTime"].AsInt64, new TimeSpan(doc["Offset"].AsInt64))
);