Question

I create manually a BsonDocument. I have to add a datetime into the document. How can I convert C# Datetime to MongoDB format ?

Thanks

Was it helpful?

Solution

You no need to do anything. Just assign date to bson document:

var bsonDocument = new BsonDocument();
bsonDocument["date"] = DateTime.Now;

Driver will automatically convert your datetime to mongodb format and store in as UTC date, and will convert back to your local timezone back when you will read it (actually you can change this behavior via driver settings). So, take it in the mind that dates in mongodb always in UTC format.

Documentation about mongodb DateTime:

The BSON Date/Time data type is referred to as "UTC DateTime" in the BSON spec.

A BSON Date value stores the number of milliseconds since the Unix epoch (Jan 1, 1970) as a 64-bit integer. v2.0+ : this number is signed so dates before 1970 are stored as a negative numbers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top