0

I'm working with MongoDB, and found weird behaviour (at least for me). I got time difference when inserting from C# and retrieve it from MongoDB.

My entity :

[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; }

Timestamp was inserted using below code :

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;
}
  • Inserted data : {4/30/16 9:04:36 PM}
  • Retrieval data : {4/30/16 2:04:36 PM}

I have tried to modify the entities by adding Bson attribute, but it was not working:

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

Why this behaviour happened ? and how can I fix this ?

Gerry Gry
  • 182
  • 5
  • 17

1 Answers1

0

I managed to found the answer after changing my keyword during search on this site and google.

According to MongoDB manual : https://docs.mongodb.org/manual/tutorial/model-time-data/

Time is defaulted to UTC, that's why I got 7 hours difference (my bad to not look into the manual first) So I managed to fix my problem by adding BsonAttribute to the Datetime as below :

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

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

Community
  • 1
  • 1
Gerry Gry
  • 182
  • 5
  • 17