Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct insert DateTime from c# to mongodb

I try to insert local time in MongoDB

var time = DateTime.Now; // 03.05.2014 18:30:30

var query = new QueryDocument
{
   { "time", nowTime}
};

collection3.Insert(query);

But in database I see ISODate("2014-05-03T15:30:30.170Z"),
that must be ISODate("2014-05-03T18:30:30.300Z").
Please help me!

like image 461
user3577947 Avatar asked May 03 '14 15:05

user3577947


People also ask

How do you insert a date value?

Always use ANSI default string literal format for date i.e. YYYY-MM-DD like below. INSERT INTO EMPLOYEE (EMPID, FULLNAME, DESIGNATION, JOINING, SAL, DEPTNAME) VALUES(8976, 'JOHN', 'JOE', 'ANALYST', '1990-12-12', 30000, 'Analytics'); It will insert your data in RDBMS i.e. MySQL, PostgreSQL, SQL Server.

What is the syntax in inserting a date field?

The proper format of a DATE is: YYYY-MM-DD.

What is datetime in C sharp?

DateTime is a structure that can never be null. From MSDN: The DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini, or A.D. (also known as Common Era, or C.E.) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) DateTime? can be null however.


2 Answers

Just define the "Kind" of the DateTime by the "BsonDateTimeOptions" attribute and set it to local:

[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime SomeDateProperty {get;set;}
like image 77
und3rd09 Avatar answered Sep 20 '22 18:09

und3rd09


I think you're getting confused by time zones. The Z at the end of the string indicates that it's in UTC. When you posted this question, it was just after 15:30 UTC.

I strongly suspect that the correct instant in time is being recorded - but it's being recorded as an instant in time without reference to a particular time zone. You can then convert that to whatever time zone you want later on, but recording the UTC time is almost always the correct approach.

As an aside, you can make this clearer by using UtcNow to start with. That way it's more obvious that you're not trying to obtain a "local" time.

Looking at the MongoDB documentation, it seems that the internal representation is simply a number of milliseconds since the Unix epoch - so again, that has no indication of time zone or an offset between UTC and local time. If you want to store a value which can be converted back to the local time you saw when it was recorded (even if you're now in a different time zone) you should store a time zone ID and/or the UTC offset as a separate value. That's not needed terribly often, but it's an option.

like image 43
Jon Skeet Avatar answered Sep 21 '22 18:09

Jon Skeet