受欢迎的博客标签

C# MongoDB query 8 hour time difference problem repair

Published

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:

 public  class MongoDbDataProvider
    /// <summary>
    {
        //mongodb 数据库
        public  MongoClient client = null;
        public IMongoDatabase database = null;
        public  MongoDbDataProvider()
        {
            //解决时间差的问题
           // MongoDB.Bson.Serialization.BsonSerializer.RegisterSerializer(typeof(DateTime), new MongoDB.Bson.Serialization.Serializers.DateTimeSerializer(DateTimeKind.Local));

            MongoClient client = new MongoClient("mongodb://localhost:27017");
            IMongoDatabase database = client.GetDatabase("Stock");


            //  var collection = database.GetCollection<Stockso.Core.Domain.Stocks.Stock>("Stock");
        }

        public  IMongoDatabase GetDatabase()
        {
            return database;
        }

    }

//中文:调整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;
} .