2016-04-30 41 views
0

我正在使用MongoDB,並發現奇怪的行爲(至少對我而言)。從C#插入並從MongoDB檢索時,我有時間差異。從C#插入後從mongodb中檢索不同的時間戳

我的實體:

public bool Insert(AccountCategories _input) 
{ 
    _input = new AccountCategories(); 
    _input.CreatedBy = "super-admin"; 
    _input.CreatedTime = DateTime.Now; 
    _input.Id = new ObjectId(); 
    _input.IsActive = true; 
    _input.Name = "test-name"; 

    var _result = _repo.Insert(_input); 

    return _result; 
} 
  • 插入的數據:{16年4月30日下午9點04分36秒}
  • 檢索

    [BsonId] 
    public ObjectId Id { get; set; } 
    public bool IsActive { get; set; } 
    public string CreatedBy { get; set; } 
    public DateTime CreatedTime { get; set; } 
    public string Name { get; set; } 
    

    時間戳用下面的代碼插入數據:{4/30/16 2:04:36 PM}

我試圖通過添加Bson屬性來修改實體,但它不起作用:

[BsonRepresentation(BsonType.Document)] 
public DateTime CreatedTime { get; set; } 

爲什麼會發生這種情況?我該如何解決這個問題?

回答

0

在本網站和谷歌搜索過程中更改我的關鍵字後,我設法找到答案。

據MongoDB的手冊: https://docs.mongodb.org/manual/tutorial/model-time-data/

時間默認爲UTC,這就是爲什麼我得到了7的小時差(我不好不看入手動頭) 所以我設法通過增加BsonAttribute來解決我的問題於日期時間,如下:

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

源:Dealing with how MongoDB stores DateTime when used with Service Locator Pattern