数据库
首页 > 数据库> > MongoDB C#驱动程序和DateTime字段

MongoDB C#驱动程序和DateTime字段

作者:互联网

我正在使用C#驱动程序将文档插入MongoDB集合,当我调试应用程序时,其中一个字段类型与DateTime我在“FrameTimeStamp”字段中看到服务器时间我将传递给Mongo,这是我的代码:

FrameDocument frameDoc = new FrameDocument();
frameDoc.Frame = imageBA;
frameDoc.EventCodeId = 1;
frameDoc.SesionId = 1;
frameDoc.FrameTimeStamp = DateTime.Now;
frameDoc.ServerUserId = (int)toMongoDt.Rows[0]["ServerUserId"];
frameDoc.TraderId = (int)toMongoDt.Rows[0]["TraderId"];
frameDoc.ActivePick = (int)toMongoDt.Rows[0]["ActivePick"];
frameDoc.TraderName = (string)toMongoDt.Rows[0]["TraderName"];
frameDoc.ServerUserName = (string)toMongoDt.Rows[0]["ServerUserName"];

var mongoCon = "mongodb://127.0.0.1";
MongoClient client = new MongoClient(mongoCon);
var db = client.GetDatabase("Video");

var frameCollection = db.GetCollection<FrameDocument>("Frame");
frameCollection.InsertOne(frameDoc);

在shell中,当我读取数据时,我会看到以下格式:
 2016-08-14T06:10:3​​3.295Z并且时间不是服务器时间,它的UTC,我怎么能强制mongo写入DateTime,因为我通过它,?

解决方法:

按照CSHARP-185

MongoDB stores all DateTimes in UTC. Any local times you supply are
converted to UTC when stored in the database. The recommended approach
is to always convert DateTime values to UTC yourself before storing
them in the database, that way you are in full control. You can also
tell the C# driver that you want to work in LocalTime, like this:

[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime Date
{ get; set; }

标签:c,mongodb,datetime-format
来源: https://codeday.me/bug/20190716/1475049.html