我在UWP应用程序中使用SQLite.NET with Extensions来存储包含DateTime字段的对象,我得到了奇怪的结果。似乎日期与它们应该存在的时间相隔几个小时,有时将日期时间推到第二天。
我正在存储一个名为Record的POCO类,它包含看起来像这个
的Situation对象public class Situation
{
[PrimaryKey, AutoIncrement]
public int SituationId { get; set; }
public DateTime DateTime { get; set; }
public string Description { get; set; }
}
Record类包含的情况是使用SQLite通过类似的存储库模式存储的(我只包含了相关的方法):
internal class Repository<T> : IRepository<T> where T : class
{
private SQLiteAsyncConnection asyncConn;
public Repository(SQLiteAsyncConnection conn)
{
asyncConn = conn;
}
public async Task<T> GetByIdAsync(int id)
{
var entity = await asyncConn.GetWithChildrenAsync<T>(id);
return entity;
}
public async Task InsertOrUpdateAsync(T entity)
{
await asyncConn.InsertOrReplaceWithChildrenAsync(entity);
}
}
最后,我使用ConnectionManager类获取了Repository的AsyncConnection:
public class ConnectionManager
{
public static readonly string FileName = "db.sqlite";
private static string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
public static SQLiteAsyncConnection GetAsyncConnection()
{
var connString = new SQLiteConnectionString(path, storeDateTimeAsTicks: true);
var connWithLock = new SQLiteConnectionWithLock(new SQLitePlatformWinRT(), connString);
return new SQLiteAsyncConnection(() => connWithLock);
}
}
此AsyncConnection将DateTimes存储为刻度,我怀疑这可能是问题的根源。
在一种情况下,在使用Repository.InsertOrUpdateAsync存储Record对象之前,Situation.DateTime具有以下值:
DateTime = {2016-07-01 12:59:59 PM}
Ticks = 636029747990010000
但是,使用Repository.GetByIdAsync拉取记录,DateTime值如下:
DateTime = {2016-07-01 4:59:59 PM}
Ticks = 636029891990010000
正如您所看到的,SQLite存储DateTime的方式有所不同。 Ticks字段已更改,从而导致新的日期。我不是百分之百确定这是为什么。我知道DateTime可能存在准确性问题,但如果将DateTimes存储为Ticks,那么Ticks字段是否应该匹配?为什么他们会改变?
假设我必须将DateTimes存储为刻度,我该如何解决此问题?我想把DateTime小时设置为12,这样可以在不改变日期的情况下增加或减少几个小时,但这显然不太理想。
任何帮助将不胜感激。 :)
答案 0 :(得分:1)
我制作了一个演示并使用Ticks来存储DateTime
。出现同样的问题。我调试了收到的DateTime
对象的Situation
属性。事实证明DateTime.Kind
是Utc
。所以这是一个时区问题,SQLite默认将DateTime
转换为UTC时间。
要解决此问题,您可以使用DateTime.ToLocalTime获取正确的本地时间。
以下是代码:
if (situation.DateTime.Kind == DateTimeKind.Utc)
{
situation.DateTime = situation.DateTime.ToLocalTime();
}