如何使用c#将mongodb BsonDateTime(UTC)转换为本地时间

时间:2017-04-19 15:28:37

标签: c# mongodb datetime

在我的C#控制台应用程序项目中,我使用MongoDB.Driver.2.4.3连接到MongoDB 3.2.10。

我如何转换" playerInBrazil.birthdate"在我的代码中定义为BsonDateTime(我相信这是UTC)到我的本地日期时间值(东部标准时间)?

我试图做减法操作(不允许)和DateTime.ToLocalTime方法()但是无法使它工作。

static void Main(string[] args)
    {
        DateTime myTimeConvert = DateTime.Now;
        var client = new MongoClient("mongodb://localhost:27017");
        var DB = client.GetDatabase("football");

        var players = DB.GetCollection<Player>("players");

        var playersInBrazil = players.AsQueryable()
                         .Where(p => p.country == "Brazil");
        foreach (var playerInBrazil in playersInBrazil)
        {
            Console.Write(playerInBrazil.firstname);
            Console.Write(" birthdate in UTC time is ");
            Console.Write(playerInBrazil.birthdate);
            Console.Write(" and in my local time is ");
            //myTimeConvert =?
            Console.WriteLine(myTimeConvert);

        }

    }

    internal class Player
    {
        public ObjectId Id { get; set; }
        public string firstname { get; set; }
        public BsonDateTime birthdate { get; set; }
        public string country { get; set; }
        public double goals { get; set; }
    }
}

1 个答案:

答案 0 :(得分:0)

BsonDateTime有一个.ToLocalTime()方法,它返回一个DateTime

此处有更多信息http://api.mongodb.com/csharp/current/html/M_MongoDB_Bson_BsonDateTime_ToLocalTime.htm