首页 > 解决方案 > Xamarin.Forms - 在显示之前从 SQLite 更改值(日期时间)

问题描述

我有一个问题,希望你能帮助我。

我在 Xamarin.Forms 中的应用程序可以添加到 sqlite:

public class Product
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }
        public string Text { get; set; }
        public string Details { get; set; }
        public string Date { get; set; }
    }

使用以下方法添加此数据:

<Editor Placeholder="Enter text" Text="{Binding Text}" />
<Editor Placeholder="Enter details" Text="{Binding Details}" />
<DatePicker Date="{Binding Date, Mode=TwoWay}" Format="dd/MM/yyyy" />

在另一个页面上,我使用 ListView 显示它们:

<Label Text="{Binding Text}" />
<Label Text="{Binding Details}" />
<Label Text="{Binding Date}" />

日期显示格式为:01/01/2017 00:00:00

我希望能够在此日期文本出现之前对其进行更改。例如,我想将此字符串日期转换为 DateTime 对象并计算从今天到给定日期还剩下多少天。

标签: c#sqlitexamlxamarin.forms

解决方案


首先,将日期存储为数据库中的 DateTime 类型而不是字符串通常是最佳实践。

也就是说,有很多方法可以解决这个问题。一种是将只读属性添加到您的模型或 ViewModel

public class Product
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    public string Text { get; set; }
    public string Details { get; set; }
    public string Date { get; set; }

    // tell sqlite to ignore this column
    [Ignore]
    public int DaysLeft {
      get {
        // should add error handling here in case
        // date format is bad
        var date = DateTime.Parse(Date);
        // diff will be a TimeSpan
        var diff = DateTime.Now - date;
        // might want to add logic to handle negative values
        return diff.Days;
      }
    }
}

推荐阅读