簡體   English   中英

使用 SQLite 在 Xamarin.Forms 中顯示日期時間

[英]Displaying DateTime in Xamarin.Forms with SQLite

我正在為學校項目創建 Xamarin.Forms 應用程序。 此項目顯示包含開始和結束日期的學期列表(6 個月的時間段)。 術語列表顯示沒有問題,但日期未按預期顯示:所有日期都是 01/01/0001。 術語表是:

    Id          TermName    StartDate   EndDate   
----------  ----------  ----------  ----------
1           Term 1      2020-01-01  2020-06-30
2           Term 2      2020-07-01  2020-12-31
3           Term 3      2021-01-01  2021-06-30
4           Term 4      2021-07-01  2021-12-31
5           Term 5      2022-01-01  2022-06-30
6           Term 6      2022-07-01  2022-12-31

由於 SQLite 沒有特定的 DATETIME 數據類型,因此我將 StartDate 和 EndDate 存儲為 TEXT 數據類型,但 terms.cs 模型文件使用 DateTime 數據類型。 在術語列表的加載處放置一個斷點顯示: Breakpoint data

條款.cs文件:

[Table("Terms")]
    public class Terms
    {
        public int Term { get; set; }
        public string TermName { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }

MainPage.xaml.cs 文件:

protected override void OnAppearing()
        {
            base.OnAppearing();
            using (SQLiteConnection conn = new SQLiteConnection(App.DBLocation))
            {
                conn.CreateTable<Terms>();
                var terms = conn.Table<Terms>().ToList();
                TermsListView.ItemsSource = terms;
                TermsListView.SelectedItem = null;
            }
        }

如何從我的表中獲取 StartDate 和 EndDate 以正確顯示在我的 ListView 中?

在 ListView 中試試這個代碼

     <Label
                                        FontSize="18"
                                        HorizontalOptions="Center"
                                        HorizontalTextAlignment="Center"
                                        Text="{Binding StartDate, StringFormat='{0:dd/MM/yyyy}'}" />
<Label
                                        FontSize="18"
                                        HorizontalOptions="Center"
                                        HorizontalTextAlignment="Center"
                                        Text="{Binding EndDate, StringFormat='{0:dd/MM/yyyy}'}" />

由於您將其存儲為string ,因此無法將值分配給DateTime屬性(無自動轉換)。 所以他們保留他們的默認日期。 將屬性更改為:

 public class Terms
    {
        public int Term { get; set; }
        public string TermName { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }
    }

然后顯示這些屬性或將值轉換為真正的DateTime類型:

public class Terms
        {
            public int Term { get; set; }
            public string TermName { get; set; }
            public string StartDate { get; set; }
            public string EndDate { get; set; }
            public DateTime RealStartDate => DateTime.Parse(StartDate);
            public DateTime RealEndDate => DateTime.Parse(EndDate);
        }

Parse方法未經我測試,但如果結果不是您需要的,您可以查找正確的語法。

在您的視圖中,您應該使用RealStartDateRealEndDate屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM