Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB C# driver and DateTime field

I'm inserting a document to MongoDB collection using C# driver, one of the fields types vs a DateTime when i debug the application i see the server time in the "FrameTimeStamp" fields i'm passing to Mongo, this is my code:

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);

in the shell when I'm reading the data i see it in the following format: 2016-08-14T06:10:33.295Z and the time is not the server time, its UTC, how can i force mongo to write the DateTime as i pass it,?

like image 885
Shimon Wiener Avatar asked Sep 04 '16 14:09

Shimon Wiener


1 Answers

as per 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; }
like image 51
profesor79 Avatar answered Oct 26 '22 19:10

profesor79