Set MongoDB GMT Time in C#
2014/06/071 min read
bookmark this
Table of Contents
Introduction
When working with MongoDB and C#, it is important to store dates in UTC format for consistency. This post shows how to save DateTime as GMT/UTC time in MongoDB using the C# driver.
Save DateTime as GMT Time to MongoDB
You can set the UTC date at the property level and assign it when inserting.
Property Attribute to Save Time as UTC
[BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
public DateTime UpdateDate { get; set; }
Save Date When Inserting to MongoDB
table.CreateDate = DateTime.UtcNow;
Reference
Conclusion
By using the [BsonDateTimeOptions(Kind = DateTimeKind.Utc)] attribute and DateTime.UtcNow, you can ensure that all dates stored in MongoDB are in GMT/UTC format, which helps maintain consistency across different time zones.