Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Datetime from C# to MongoDB

Tags:

c#

mongodb

I try to save Datetime value from C# to MongoDB with value :

DateTime.ParseExact("10/02/2015", "dd/MM/yyyy", CultureInfo.InvariantCulture)

But in MongoDB show up :

ISODate("2015-02-09T17:00:00.000Z")

I don't know why MongoDB result later than one day (date : 9) while my date is 10. Thanks for your reading my question

Update 1 : As #mnemosyn's answer i do some change :

DateTime.SpecifyKind((DateTime.ParseExact("20/07/2015", "dd/MM/yyyy", CultureInfo.InvariantCulture)), DateTimeKind.Utc)

Result : ISODate("2015-07-20T00:00:00.000Z")

More detail : DateTime.ToLocalTime Method

like image 395
Hana Avatar asked May 13 '15 03:05

Hana


1 Answers

The problem is that the parsed date is not considered a UTC date. 02-09+7h is exactly 02-10...

DateTime has a property called Kind which of type DateTimeKind. These can be Local, UTC or Unspecified. If the string you're parsing doesn't indicate which one it is, the returned DateTime.Kind will be Unspecified. The MongoDB driver then converts this to UTC because that is, more often than not, what people expect when they think of DateTime.

Note that the mantra 'always store UTC in the database' isn't always true, e.g. for a bus schedule.

like image 188
mnemosyn Avatar answered Nov 13 '22 15:11

mnemosyn