If I have a given date range (DateFrom and DateTo), how can I get all the dates within the date range?
            Asked
            
        
        
            Active
            
        
            Viewed 639 times
        
    0
            
            
         
    
    
        Leong
        
- 229
- 2
- 11
2 Answers
1
            
            
        As per How to add days and hours to a date-time variable? you just use DateUtils.IncDay(). Example:

type
  TForm1 = class(TForm)
    lblFrom: TLabel;
    dtpFrom: TDateTimePicker;
    lblTo: TLabel;
    dtpTo: TDateTimePicker;
    cbnAll: TButton;
    lbxAll: TListBox;
    procedure cbnAllClick(Sender: TObject);
  end;
var
  Form1: TForm1;
implementation
{$R *.dfm}
uses
  DateUtils;
procedure TForm1.cbnAllClick(Sender: TObject);
var
  vFrom, vDay, vTo: TDate;
begin
  // From the DateTimePicker controls
  vFrom:= dtpFrom.Date;
  vTo:= dtpTo.Date;
  // Starting with "From", ending at "To"
  vDay:= vFrom;
  repeat
    // Add current iteration as text to listbox
    lbxAll.Items.Add( DateToStr( vDay ) );
    // Increase date's day by 1, automatically switching month and year, if needed
    vDay:= DateUtils.IncDay( vDay, 1 );
  until vDay> vTo;
end;
 
    
    
        AmigoJack
        
- 5,234
- 1
- 15
- 31
- 
                    Would benefit from a (`try..finally`-protected) `BeginUpdate`..`EndUpdate` pair if the range is big. – Andreas Rejbrand May 14 '22 at 09:31
0
            
            
        The integer part of a TDate or TDateTime value is the day number ( the number of days that have passed since
1899-12-30). Using this information an iteration for all dates within a date range can look like this:
program IterateDateRangeProj;
{$APPTYPE CONSOLE}
uses
  System.SysUtils,DateUtils;
procedure IterateDateRange( DateFrom,DateTo : TDate);
var
  iDate : TDate;
begin
  for var i := Trunc(DateFrom) to Trunc(DateTo) do begin
    iDate := i;
    WriteLn(DateToStr(iDate));
  end;
end;
begin
  IterateDateRange(ToDay,Tomorrow);
  ReadLn;
end.
 
    
    
        LU RD
        
- 34,438
- 5
- 88
- 296