Donate

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
[BsonElement]
[Required(ErrorMessage = "Activity Date required")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ActivityDate { get; set; }
to BsonDateTimeOptions and set it's kind to local.
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
[Required(ErrorMessage = "Activity Date required")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ActivityDate { get; set; }
Option two is to retain the BsonElement attribute of the date property.
[BsonElement]
[Required(ErrorMessage = "Activity Date required")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ActivityDate { get; set; }
and in your method to retrieve the collection, specify the date returned as UTC and then cast the UTC date as LocalTime.
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 stored in MongoDB as local.
MongoDB Getting UTC Date Instead Of Local Date In ASP.NET MVC
Dates retrieved are UTC and not local.
MongoDB Getting UTC Date Instead Of Local Date In ASP.NET MVC
After applying solutions one or two.
MongoDB Getting UTC Date Instead Of Local Date In ASP.NET MVC

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input