简体   繁体   English

从C#正确插入DateTime到mongodb

[英]Correct insert DateTime from c# to mongodb

I try to insert local time in MongoDB 我尝试在MongoDB中插入本地时间

var time = DateTime.Now; // 03.05.2014 18:30:30

var query = new QueryDocument
{
   { "time", nowTime}
};

collection3.Insert(query);

But in database I see ISODate("2014-05-03T15:30:30.170Z") , 但是在数据库中,我看到了ISODate("2014-05-03T15:30:30.170Z")
that must be ISODate("2014-05-03T18:30:30.300Z") . 必须为ISODate("2014-05-03T18:30:30.300Z")
Please help me! 请帮我!

I think you're getting confused by time zones. 我认为您对时区感到困惑。 The Z at the end of the string indicates that it's in UTC. 字符串末尾的Z表示它位于UTC中。 When you posted this question, it was just after 15:30 UTC. 当您发布此问题时,它是在世界标准时间15:30之后。

I strongly suspect that the correct instant in time is being recorded - but it's being recorded as an instant in time without reference to a particular time zone. 我强烈怀疑正在记录正确的时间-但它被记录为不参考特定时区的时间。 You can then convert that to whatever time zone you want later on, but recording the UTC time is almost always the correct approach. 然后,您可以转换为以后想要的任何时区,但是记录UTC时间几乎总是正确的方法。

As an aside, you can make this clearer by using UtcNow to start with. UtcNow ,您可以先使用UtcNow使其更清晰。 That way it's more obvious that you're not trying to obtain a "local" time. 这样一来,您显然不会尝试获取“本地”时间。

Looking at the MongoDB documentation, it seems that the internal representation is simply a number of milliseconds since the Unix epoch - so again, that has no indication of time zone or an offset between UTC and local time. 查看MongoDB文档,似乎内部表示仅是自Unix纪元以来的毫秒数,因此,同样,它不表示时区或UTC与本地时间之间的偏移量。 If you want to store a value which can be converted back to the local time you saw when it was recorded (even if you're now in a different time zone) you should store a time zone ID and/or the UTC offset as a separate value. 如果您想存储一个可以转换为记录时所看到的本地时间的值(即使您现在处于不同的时区),则应将时区ID和/或UTC偏移量存储为单独的值。 That's not needed terribly often, but it's an option. 这并不是经常需要的,但这是一种选择。

The MongoDB driver is converting your DateTime to UTC. MongoDB驱动程序正在将您的DateTime转换为UTC。

If you don't want to bother with time zones, you could change the kind to UTC: 如果您不想打扰时区,可以将类型更改为UTC:

time = DateTime.SpecifyKind(time, DateTimeKind.Utc);

I would not recommed this because the database will store a "wrong" Date, but it will show you ISODate("2014-05-03T18:30:30.170Z"). 我不建议这样做,因为数据库将存储“错误的”日期,但是它将显示ISODate(“ 2014-05-03T18:30:30.170Z”)。

Just define the "Kind" of the DateTime by the "BsonDateTimeOptions" attribute and set it to local: 只需通过“ BsonDateTimeOptions”属性定义DateTime的“种类”并将其设置为本地:

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

It could work with: 它可以与:

    DateTime t = DateTime.Now;

    var update = Builders<BsonDocument>.Update
    .Set("key1", t.ToUniversalTime())
    .CurrentDate("key_updatetime");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM