简体   繁体   中英

Convert MongoDB BsonTimestamp to C# DateTime

What is the proper way to convert a BsonTimestamp field to a C# DateTime type?

This is for data in MongoDB's oplog collection and using the MongoDB C# driver.

I believe the accepted answer in slightly off as Unix Epoch must be in UTC format.

var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

From BsonTimestamp to DateTime

var target = unixEpoch.AddSeconds(bsonTimestamp.Timestamp - 18000);

From DateTime to BsonTimestamp

var target = DateTime.UtcNow;
var diff = target.ToUniversalTime() - unixEpoch;
var seconds = (diff.TotalMilliseconds + 18000000) / 1000;
var ts = new BsonTimestamp((int)seconds, 1);

You need to use target.ToUniversalTime() to ensure the incoming parameter, if any, is always positioned for UTC.

MongoDB's Timestamp is the elapsed seconds since the Unix epoch (1970/1/1). Therefore, the conversion from Timestamp to DateTime is like this:

DateTime datetime = new DateTime(1970, 1, 1).AddSeconds(bsonTimestamp.Timestamp);

In terms of Value / Timestamp properties, they are implmented in both constructors of BsonTimestamp in https://github.com/mongodb/mongo-csharp-driver .

Constructor 1:

public BsonTimestamp(long value)
{
    _value = value;
}

Constructor 2:

public BsonTimestamp(int timestamp, int increment)
{
    _value = (long)(((ulong)(uint)timestamp << 32) | (ulong)(uint)increment);
}

Property:

public long Value
{
    get { return _value; }
}

public int Timestamp
{
    get { return (int)(_value >> 32); }
}

Since you are getting the timestamp records from oplog, their format would be like this:

Timestamp(1406171938, 1) 

AS the second number ( increment ) is an ordinal number to make the Timestamp unique according to MongoDB reference , you should use Timestamp property I think.

If you are using a BSON document:

DateTime dateTime = doc["BSONdateTime"].AsDateTime;

where "dateTime" is the variable you want to set, "doc" is the BSON document you extracted from MongoDB, and "BSONdateTime" is the key that you want to extract the date and time from.

I haven't tried this myself, but I was able to extract string values from BSON documents in MongoDB using:

string name = doc["name"].AsString;

I would also recommend you look into POCO, as this makes type conversion a lot easier and less boilerplate.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM