delphifiremonkeydelphi-10.4-sydneylivebindings

How to Show images in ListView depends on the date


I'm Using Delphi Sydney 10.4 FMX, I have a ListView connected to a Database with liveBinding, ImageList that has 3 images.

In the ListView, I Have 3 Fields: Image, Expiry, Domain.

The Expiry and Domain are filled from the Database, but the image I want to show depends on the date, example :

Expiry = date of today or before today: I want to show imageindex 0

Expiry = from Tomorrow until 30 days from Today: I want to show imageindex 1

Expiry = 31 Days Later from today: I want to show imageindex 2

procedure TForm1.DomainsListViewUpdateObjects(const Sender: TObject;
  const AItem: TListViewItem);
begin
  var DT : TDateTime;
  DT := Now;
  if DomainsListView.Items[DomainsListView.ItemIndex].Data['expiry'].AsString < datetostr(DT+30) then
    DomainsListView.Items[DomainsListView.ItemIndex].Data['image'] := 1
  else if DomainsListView.Items[DomainsListView.ItemIndex].Data['expiry'].AsString < DateToStr(DT) then
    DomainsListView.Items[DomainsListView.ItemIndex].Data['image'] := 0
  else if DomainsListView.Items[DomainsListView.ItemIndex].Data['expiry'].AsString > DateToStr(DT+31) then
    DomainsListView.Items[DomainsListView.ItemIndex].Data['image'] := 2
end;

I used this code, but does not works correctly


Solution

  • You are comparing String values, which doesn't work to compare dates. You should be comparing TDateTime values instead, as well as paying more attention to the order of your comparisons.

    Try something more like this instead:

    uses
      ..., System.SysUtils, System.DateUtils;
    
    procedure TForm1.DomainsListViewUpdateObjects(const Sender: TObject;
      const AItem: TListViewItem);
    begin
      var Item: TListViewItem := DomainsListView.Items[DomainsListView.ItemIndex]; // or: DomainsListView.Selected
      var dtToday: TDateTime := System.DateUtils.Today;
      var dtExpiry: TDateTime := System.SysUtils.StrToDate(Item.Data['expiry'].AsString);
      if dtExpiry <= dtToday then
        Item.Data['image'] := 0 
      else if dtExpiry < (dtToday+31) then
        Item.Data['image'] := 1
      else
        Item.Data['image'] := 2;
    end;