我过去使用过一些 SQLite,我非常喜欢它,所以我想将它用于一个新项目。
第 1 步是创建数据库,我需要创建一个 DateStamp
字段,我在其中放置事件发生时间的时间戳。
在SQLite Documentation ,日期和时间数据类型定义如下:
1.2 Date and Time Datatype
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
- TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
- REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
- INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
我不想将日期保存为文本,并且由于 Windows DateTime 对象不会回到公元前 4714 年 11 月 24 日,我想我只能将 DateTime 值存储为 INTEGER。
那么,如何将 DateTime 存储为整数?我会得到基准日期和我想要的日期之间的TimeSpan
,提取天数并存储吗?
// is this a UTC date?
private static readonly DateTime utc1970_01_01 = new DateTime(1970, 1, 1);
public static double GetIntDate(DateTime dateTime) {
// FYI: subtracting dates in .NET returns a time span object
return (dateTime - nov24_4714bc).TotalSeconds;
}
对吗?这就是其他人使用 SQLite 所做的事情吗?
它还说 SQLite 以 UTC 时间存储日期时间,所以我需要在此基础上再次转换。
肯定有人以前做过这个。我很高兴看到有人已经制作了可以处理这些输入的工具。 SQLite 有一些 built in functions ,但我真的不明白如何使用它们。
已解决:
好吧。
能这么简单吗?
public static long ToFileTimeUtc(DateTime dateTime) {
return dateTime.ToFileTimeUtc();
}
public static DateTime FromFileTimeUtc(long fileTimeUtc) {
return DateTime.FromFileTimeUtc(fileTimeUtc);
}
评论?
我不能那样做吗?
最佳答案
您是否可以使用 FileTime 取决于除您的应用之外是否有其他任何东西访问数据。 FileTime 表示自 1601 年 1 月 1 日(UTC)以来的 100 纳秒间隔数。
因此,您需要确保整数是 SQLLite 中的 8 字节整数,以便存储整个值。
只要您的应用是处理这些数据的唯一应用,并且您始终使用 FileTime,就没有问题。如果其他人将访问此数据,并且他们能够理解 FileTime,并且他们知道这就是它,那么也没有问题。
关于c# - 将日期时间作为整数存储和检索到 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11602591/