Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save date properly?

I'm trying to save date (using C# official driver):

val = DateTime.Parse(value).Date; //Here date is {11/11/2011 12:00:00 AM} var update = Update.Set("Date", val); ... 

When I select Date from the database, the value is {11/10/2011 10:00:00 PM}

How to save only the date I want?

like image 775
1gn1ter Avatar asked Nov 09 '11 10:11

1gn1ter


People also ask

How does MongoDB save date?

MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed.

Does MongoDB store date in UTC?

Overview. MongoDB stores times in UTC by default, and will convert any local time representations into this form. Applications that must operate or report on some unmodified local time value may store the time zone alongside the UTC timestamp, and compute the original local time in their application logic.

How does MongoDB store dates in node?

The best format to store date and time in MongoDB is native javascript Date() or ISO date format as it internally converts it into BSON native Date object.


1 Answers

c# driver by default (without extra settings) saving local dates as utc date into database (date - time zone offset) but reading back without any action (so, utc date).

Because of this when you loading datetime from database you receive diff in 2 hours (your timezone offset). There are two approaches how to say to mongodb c# driver convert utc dates to local timezone dates during deserialization:

1.through the attributes for particular date field:

[BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime SomeDateProperty {get;set;} 

2.through global settings for all datetime fields (default is UtcInstance):

DateTimeSerializationOptions.Defaults = DateTimeSerializationOptions.LocalInstance; 

Once you will do #1 or #2 you will see local date.

Update:


#2 is obsolete in latest driver version so use code below instead:

BsonSerializer.RegisterSerializer(typeof(DateTime),               new DateTimeSerializer(DateTimeSerializationOptions.LocalInstance)); 

Update:


#2 has changed again:

BsonSerializer.RegisterSerializer(typeof(DateTime), DateTimeSerializer.LocalInstance); 
like image 184
Andrew Orsich Avatar answered Sep 19 '22 09:09

Andrew Orsich