我有以下通过的测试:
namespace MongoDateTest
{
[TestFixture]
public class DateTesting
{
public class TestEntity
{
public string Id { get; set; }
public string StringTest { get; set; }
public DateTime DateTest { get; set; }
}
[Test]
public void MongoDateConversion()
{
const string connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("test");
var collection = database.GetCollection<TestEntity>("entities");
var entity = new TestEntity {
Id = "1",
StringTest = "Test",
DateTest = new DateTime(2013, 10, 13) //this is the date
};
collection.Save(entity);
var id = entity.Id;
var query = Query<TestEntity>.EQ(e => e.Id, id);
var entityNew = collection.FindOne(query);
Assert.AreEqual(entityNew.Id, entity.Id);
Assert.AreEqual(entity.StringTest, entityNew.StringTest);
//Assert.AreEqual(entity.DateTest,entityNew.DateTest);
// This gives one day error:
// Expected: 2013-10-13 00:00:00.000
// But was: 2013-10-12 22:00:00.000
//Assert.AreEqual(entity.DateTest.ToLocalTime(),entityNew.DateTest.ToLocalTime());
// This gives a 2 hours error.
// Expected: 2013-10-13 02:00:00.000
// But was: 2013-10-13 00:00:00.000
Assert.AreEqual(entity.DateTest, entityNew.DateTest.ToLocalTime());
}
}
}
如果我取消对任何 Asserts.AreEqual 的注释,我会收到错误消息(如下注释)。
保存的实体是:
{
"_id" : "1",
"StringTest" : "Test",
"DateTest" : ISODate("2013-10-12T22:00:00Z")
}
我知道这可能与 ISODate 和 UTC(我在 UTC+1)有关,但我有点恼火的是我的日期在集合中保存了一天的差异,并且要求我在任何时候获取一些数据时转换为 localTime与日期。
这种行为的原因是什么,有没有办法避免它?