Home > Blockchain >  Get all dates within a date range
Get all dates within a date range

Time:05-14

If I have a given date range (DateFrom and DateTo), how can I get all the dates within the date range?

CodePudding user response:

As per How to add days and hours to a date-time variable? you just use DateUtils.IncDay(). Example:

DateTimePickers and Listbox to iterate all dates per day

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;

CodePudding user response:

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.
  • Related