考虑到我有以下代码:
public class Project
{
...
public DateTime CreationDate { get; set; }
...
}
var project = new Project();
project.CreationDate = new DateTime(2020, 2, 3); // Setting 03/02/2020 date
await _mongoDbContext.Projects.InsertOneAsync(project);
插入文档后,当我将其取回时,CreationDate
属性具有03/02/2020 03:00:00值,而不是03/02/2020 00:00:00。
编辑
这就是我取回项目的方式(项目类型是一个枚举(:
var filter = Builders<Project>.Filter.Eq(x => x.ProjectType, (int)ProjectTypes.Activity);
var projects = _mongoDbContext.Projects.Find(filter).ToList();
可能的答案
看起来使用[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
注释可以解决此问题。
public class Project
{
...
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime CreationDate { get; set; }
...
}
正如@Prasad和@Kit所建议的那样。
发生这种情况是因为驱动程序在数据库中存储之前将日期时间转换为 UTC。 在此处查看源代码
最佳做法是始终在应用代码中处理 UTC,然后在向最终用户呈现数据时将其转换为本地时间。
例如,在创建记录时,您可以执行以下操作:
CreationDate = new DateTime(2020, 02, 03)
//this is not neccessary as the driver takes care of the conversion
CreationDate = new DateTime(2020, 02, 03, 0, 0, 0, DateTimeKind.Utc)
在演示时,您可以这样做:
project.CreationDate.ToLocalTime()
如果你的表示层是一些JS框架,你用UTC将数据发送到Web应用程序,JavScript在显示时将其转换为用户的本地时间。
之所以仅在应用代码中处理 UTC,是因为即使将来在多个地理位置的多台计算机上运行代码,代码也只涉及单个时区。 转换为本地时间是表示逻辑的责任。