如何正确保存日期? [英] How to save date properly?
问题描述
我正在尝试保存日期(使用C#官方驱动程序):
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);
...
当我从数据库中选择日期"时,值为{11/10/2011 10:00:00 PM}
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?
推荐答案
c#驱动程序默认情况下(无需额外设置)将本地日期作为utc日期保存到数据库中(日期-时区偏移量),但无需任何操作即可回读(因此, utc日期).
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).
因此,从数据库中加载日期时间时,您会在2小时内收到差异(您的时区偏移量).在反序列化期间,如何使用mongodb c#驱动程序将utc日期转换为本地时区日期有两种方法:
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.通过特定日期字段的属性:
1.through the attributes for particular date field:
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime SomeDateProperty {get;set;}
2.通过所有日期时间字段的全局设置(默认为UtcInstance
):
2.through global settings for all datetime fields (default is UtcInstance
):
DateTimeSerializationOptions.Defaults = DateTimeSerializationOptions.LocalInstance;
一旦您执行#1或#2操作,就会看到本地日期.
Once you will do #1 or #2 you will see local date.
更新:
#2在最新的驱动程序版本中已过时,因此请改用以下代码:
#2 is obsolete in latest driver version so use code below instead:
BsonSerializer.RegisterSerializer(typeof(DateTime),
new DateTimeSerializer(DateTimeSerializationOptions.LocalInstance));
更新:
#2再次更改:
BsonSerializer.RegisterSerializer(typeof(DateTime), DateTimeSerializer.LocalInstance);
这篇关于如何正确保存日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!