Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert C# DateTime into MongoDB format

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

Thanks

like image 210
hotips Avatar asked Feb 16 '12 10:02

hotips


1 Answers

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.

like image 57
Andrew Orsich Avatar answered Sep 30 '22 21:09

Andrew Orsich