Popular blog tags
The time stored in mongodb is the standard time UTC +0:00 and the loss of our China is +8.00.  中文:MongoDB--时区问题(差了8小时) When retrieving DateTime data in C#, it will be converted to LocalTime format, or there will always be a shortage of 8 hours. This is because MongoDB takes UTC time, and usually the system uses Local time (China), and the time zone is different.  Solution 1:Convert Utc time to Local time as follow: [csharp]  Convert.ToDateTime(doc["CreateTime"]).ToLocalTime().ToString("yyyy-MM-dd HH:mm")     Solution 2:use MongoDB.Bson.Serialization.Serializers.DateTimeSerializer as follow: using System; using MongoDB.Bson;using MongoDB.Driver; using MongoDB.Driver.Core;   namespace Stockso.Data{ public static class MongoDbDataProvider /// <summary> { public static MongoClient client = null; public static IMongoDatabase database = null; static MongoDbDataProvider() { MongoClient client = new MongoClient("mongodb://localhost:27017"); IMongoDatabase database = client.GetDatabase("CStock"); //中文:调整uct时间到本地时间 //english:adjust the uct time to local time MongoDB.Bson.Serialization.BsonSerializer.RegisterSerializer(typeof(DateTime), new MongoDB.Bson.Serialization.Serializers.DateTimeSerializer(DateTimeKind.Local)); }   example:   #region Constructors public StockDataDatabaseStockInfoService( ILogger<StockDataDatabaseStockInfoService> logger, IHttpClientFactory clientFactory ) { this._logger = logger; this._clientFactory = clientFactory; //DateTime Localize BsonSerializer.RegisterSerializer(typeof(DateTime), new DateTimeSerializer(DateTimeKind.Local)); } #endregion public static IMongoDatabase GetDatabase() { return database; } }}  Solution 3: The C# driver supports a feature that adds this feature to the time property of the entity and refers to the time zone. For example:Use MongoDB.Bson.Serialization.Attributes.BsonDateTimeOptions property [MongoDB.Bson.Serialization.Attributes.BsonDateTimeOptions(Kind=DateTimeKind.Local)]public DateTime CreateTime{get;set;} .