I am creating a Xamarin.Forms application for a school project. This project displays a list of school terms (6-month blocks of time) with the start and end dates. The list of the terms displays without issues, but the dates do not appear as expected: all dates are 01/01/0001. The terms table is:
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
Since SQLite doesn't have a specific DATETIME data type, I'm storing the StartDate and EndDate as a TEXT data type, but the terms.cs model file uses the DateTime datatype. Placing a breakpoint at the loading of the list of terms shows: Breakpoint data.
Terms.cs file:
[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 file:
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;
}
}
How do I get the StartDate and EndDate from my table to show up in my ListView correctly?
Because you store it as a string
the value cannot be assigned to the DateTime
properties (no automatic conversion). So they keep their default date.
Change the properties to:
public class Terms
{
public int Term { get; set; }
public string TermName { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
}
Then display these properties or convert the value to a real DateTime
type:
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);
}
The Parse
method is not tested by me but you can look up the correct syntax if the result is not what you need.
In you View you should then use the RealStartDate
and RealEndDate
properties