5

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

Thanks

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ! Visual Studio underlined at one time the line... but it compile and works now ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.