将正确的DateTime从C#正确插入到mongodb [英] Correct insert DateTime from c# to mongodb

查看:228
本文介绍了将正确的DateTime从C#正确插入到mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在MongoDB中插入本地时间

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

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

collection3.Insert(query);

但是在数据库中,我看到了ISODate("2014-05-03T15:30:30.170Z")
必须为ISODate("2014-05-03T18:30:30.300Z").
请帮帮我!

解决方案

我认为您对时区感到困惑.字符串末尾的Z表示它位于UTC中.当您发布此问题时,它是在世界标准时间15:30之后.

我强烈怀疑正在记录正确的时间-但是,它被记录为不参考特定时区的时间.然后,您可以将其转换到以后想要的任何时区,但是记录UTC时间几乎总是正确的方法.

顺便说一句,您可以使用UtcNow开始使它更清晰.这样一来,您显然不会尝试获取本地"时间.

查看MongoDB文档,似乎内部表示仅是自Unix纪元以来的毫秒数-如此一来,它不表示时区或UTC与本地时间之间的偏移量.如果您想存储一个值,该值可以转换回记录时所看到的本地时间(即使您现在在其他时区),则应存储时区ID和/或UTC偏移作为单独的值.并不是经常需要这种方法,但这是一种选择.

I try to insert local time in 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"),
that must be 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. When you posted this question, it was just after 15:30 UTC.

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.

As an aside, you can make this clearer by using UtcNow to start with. 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. 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. That's not needed terribly often, but it's an option.

这篇关于将正确的DateTime从C#正确插入到mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆