MongoDB Getting UTC Date Instead Of Local Date In ASP.NET MVC
Hello all!
When inserting local dates in MongoDB and retrieving them using C#, you might wonder why the date returned is inconsistent with the values stored in the database. Well, MongoDB treats those dates as UTC. So to display those dates as local, there are several solutions. Option one is to change the BsonElement attribute of a date property
to BsonDateTimeOptions and set it's kind to local.
Option two is to retain the BsonElement attribute of the date property.
and in your method to retrieve the collection, specify the date returned as UTC and then cast the UTC date as LocalTime.
Dates stored in MongoDB as local.
Dates retrieved are UTC and not local.
After applying solutions one or two.
When inserting local dates in MongoDB and retrieving them using C#, you might wonder why the date returned is inconsistent with the values stored in the database. Well, MongoDB treats those dates as UTC. So to display those dates as local, there are several solutions. Option one is to change the BsonElement attribute of a date property
[BsonElement] [Required(ErrorMessage = "Activity Date required")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime ActivityDate { get; set; }
[BsonDateTimeOptions(Kind = DateTimeKind.Local)] [Required(ErrorMessage = "Activity Date required")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime ActivityDate { get; set; }
[BsonElement] [Required(ErrorMessage = "Activity Date required")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime ActivityDate { get; set; }
public List<UserActivity> GetActivities() { mongoCollection = mongoDB.GetCollection<UserActivity>("UserActivity"); var list = mongoCollection.Find(f => true).ToList(); foreach (var item in list) { var utcDate = DateTime.SpecifyKind(item.ActivityDate, DateTimeKind.Utc); item.ActivityDate = utcDate.ToLocalTime(); } return list; }
Dates retrieved are UTC and not local.
After applying solutions one or two.
Comments
Post a Comment