Home > OS >  Comparing a Date from an SQLite Database to the current DateTime in C#, Xamarin Forms
Comparing a Date from an SQLite Database to the current DateTime in C#, Xamarin Forms

Time:03-21

So I have generated a SQLite database in Xamarin Forms. Each item has a Name and Date. I'm trying to extract the date and set it to a variable so that when each item is loaded, it will convert its date integer to DateTime and compare it to DateTime.Now. I'm not sure how to do this, and I might be missing something very elementary- I'm a complete beginner.

public LivePage()
        {
            InitializeComponent();

            
            LiveService.AddLive("2022年3月19日(土): ILLUSION FORCE presents「ILLUSION FORCE×GAUNTLET LONGSTAGE 'GACHINKO'2MAN GIG」", 20220319);
            LiveService.AddLive("2022年3月20日(日)Phantom Excaliver presents 聖剣フェス」", 202203020);
            LiveService.AddLive("2022年4月2日(土)Bad Company vol.17」", 20220402);
            LiveService.AddLive("2022年4月10日(日)VELL'z FIRE presents", 20220410);
            LiveService.AddLive("2022年4月10日(日)ILLUSION FORCE presents「ILLUSION FORCE×Amiliyah LONG STAGE 2MAN GIG」", 20220410);
            LiveService.AddLive("2022年4月29日(金・祝)渋谷メタル会 presents 渋谷メタル会フェス 2022」", 20220429);
            var Lists = LiveService.db.Table<Live>().ToList();
            MainListView.ItemsSource = Lists;
            int dateInt = Lists[2];
            DateTime dater = Convert.ToDateTime(dateInt);
            int result = DateTime.Compare(dater, DateTime.Now);
            if (result < 0)
            {
                Label.TextDecorations = TextDecorations.Strikethrough;
            }

CodePudding user response:

According to your code, it seems that there are two column in your table. So the code var Lists = LiveService.db.Table<Live>().ToList(); return the all the data in the table, but you just need the date time column which is type of int. So you can try the following code.

var list = new List<int>();         
foreach(var item in Lists)
{
  list.Add(item.SecoundColumnName);
}

In addition, the Lists is a list of Live. So it cann't convert to the int.

CodePudding user response:

Sorry I had to delete my previous comments. I was mistaken about SQLite being able to cast the date data as a DateTime object. Therefore, I can throw out a simple parser that will convert the string value of the date data.

If the data is bad then today’s date is returned, however you could return any date. You could use it like…

DateTime dater = GetDTFromString(dateInt.ToString()); 

The parser...

private DateTime GetDTFromString(string dateString) {
  if (dateString.Length >= 8) {
    string year = dateString.Substring(0, 4);
    string month = dateString.Substring(4, 2);
    string day = dateString.Substring(6, 2);
    if (DateTime.TryParse(year   ","   month   ","   day, out DateTime targetDate)) {
      return targetDate;
    }
  }
  return DateTime.Now;
}
  • Related