How can I turn UTC Timezone off for MongoDB

Viewed 2894

I'm using the extension below for MongoDB date fields because of MongoDB stores times in UTC by default.

    public static class DateTimeExtensions {
    
        public static DateTime AdjustUtcDiffByOffset(this DateTime time) {
            return time.AddHours(DateTimeOffset.Now.Offset.Hours);
        }
    }
}
All of them cause different problems although I have tried a few ways like attributes or serialization methods in .NET on the application level. I have decided to use this extension in .NET for now but I think that this is not a complete and exact solution too.

Is there any solution for this problem on the database level without being dependent on programming language wtih an adjust or something else?

EDIT

I think that I should an explain more after comments below. I already know MongoDB stores times in UTC that linked in this post as you see above. This can be useful but I don't need any UTC time zone difference in my app and I don't want to deal in Presentation Layer for every programming language separately. And also, I don't even want only one extra row or function in the other layers because of move away than base logic or business.

Let the my architecture undertaking this. I'm pretty lazy, the life is really short and the birds are flying outside :) I don't want the different fields as like as string convertings unnecessarily. I need a datetime type in the db due to I'm doing many time calculation in the app.

I'm using .NET now and therefore MongoDB .NET driver. I have tried different serialization methods but it cause another problems in the Data Access architecture. In conclusion, I can use UTC in my another app but I don't want it now and I prefer the local time when I assign to the field. I have decided to use the encapsulation below for C# especially.

    private DateTime _startTime;
    public DateTime StartTime {
        get => _startTime;
        set => _startTime = new DateTime(value.Ticks, DateTimeKind.Utc);
    }
2 Answers

I don't think it's possible from the db level. What I did, was to write custom setter for date properties which will force mongoDB to assume the time is already in UTC, thus avoid a conversion like below:

private DateTime _createdUTC;
public DateTime CreatedUtc
  {
     get
       {
         return _createdUTC;
       }
     set
       {
         _createdUTC = new DateTime(value.Ticks, DateTimeKind.Utc);
       }
  }

MongoDB always saves dates in UTC.

What you can do is indicate to the client that he must convert the date to the local date when retrieving data from the database.

You can register a serializer before instantiating the client:

BsonSerializer.RegisterSerializer(DateTimeSerializer.LocalInstance);
var client = new MongoClient(options) ...
Related