如何将仅日期值从日历日期选择器存储到 Windows 10 通用应用程序中的 SQLite 数据库

本文关键字:日期 应用程序 SQLite Windows 数据库 存储 选择器 日历 | 更新日期: 2023-09-27 18:33:04

在我的Windows 10通用应用程序中,我使用CalendarDatePicker选择一个日期:

<CalendarDatePicker x:Name="cdpStartDate" Width="150" />

在代码隐藏中,我使用以下代码将日期存储到 SQLite 数据库:

booking = new Bookings();
using (
     SQLite.Net.SQLiteConnection conn =
        new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), Common.Utils.DbPath()))
        {
        booking.StartDate = cdpStartDate.Date.ToDateTime();
        conn.Update(booking);
        }

我的表类如下所示:

[Table("Bookings")]
public class Bookings
{
    [PrimaryKey]
    public int BookingId { get; set; }
    [NotNull]
    public DateTime StartDate { get; set; }
}

调试预订值时。开始日期是 18.11.2015 00:00:00。但是,将值保存到 SQLite 数据库后,该值将转换为 17.11.2015 23:00:00。这似乎是UTC时间。我的应用程序中不需要任何时间信息,只需要日期。

如何在不转换为数据库的情况下保存日期?

谢谢乌韦

如何将仅日期值从日历日期选择器存储到 Windows 10 通用应用程序中的 SQLite 数据库

时间戳通常只是某一天的 0:00 时间。由于SQLite不会为您处理时区,因此如果您想获得纯日期,则必须输入纯(无时区)日期时间。

尝试:

booking.StartDate = cdpStartDate.Date.ToDateTime().ToUniversalTime().Date;

它实际上是 DateTime 类,它非常友好地将本地时区信息添加到其中。

GeographicRegion userRegion = new GeographicRegion();
string regionCode = userRegion.Code;
Windows.Globalization.DateTimeFormatting.DateTimeFormatter dtf = new DateTimeFormatter("shortdate", new[] { regionCode }, regionCode, CalendarIdentifiers.Gregorian, ClockIdentifiers.TwentyFourHour);
DateTimeOffset result = cdpStartDate.Date ?? DateTimeOffset.MinValue;
string shortDate = dtf.Format(result);

我使用上述方法根据本地窗口区域设置创建自定义短日期格式化程序,然后将其存储为字符串。我知道你想存储一个日期,但正如 Kai 所说,SQL 不会在没有时间部分的情况下存储日期,所以这将只给出简短格式的日期。