delphidelphi-2010calendarviewmonthcalendar

How to insert all Days in a Table for a selected Month?


I want to insert all days (startday to endday) in a Table for the selected month in a CalendarView.

So, I put a CalendarView and three Edit. And I have a Table named "Month" with a column named "Days".

Calendar

Now, I want to insert all dates between "01/10/2024" and "31/10/2024" in the Table "Month". How can I do it using a loop or another way?


Solution

  • Since you already know how to get the start and end dates as TDateTime values, it is fairly trivial to loop between them. TDateTime stores days as whole integers, so simply begin with the start date and add 1 for each day until you reach the end date, eg:

    uses
      ..., DateUtils;
    
    var
      dtSelectedDate, dtStartDate, dtEndDate, dtCurrentDate: TDateTime;
    begin
      dtSelectedDate := DateOf(CalendarView1.Date);
      dtStartDate := StartOfTheMonth(dtSelectedDate);
      dtEndDate := EndOfTheMonth(dtSelectedDate);
    
      EditMonth.Text := IntToStr(DaysInMonth(dtSelectedDate));
      EditStartDay.Text := DateToStr(dtStartDate);
      EditEndDay.Text := DateToStr(dtEndDate);
    
      dtCurrentDate := dtStartDate;
      while dtCurrentDate <= dtEndDate do
      begin
        // insert dtCurrentDate into Table
    
        dtCurrentDate := dtCurrentDate + 1;
        // or:
        dtCurrentDate := IncDay(dtCurrentDate);
      end;
    end;
    

    On the other hand, since you also know how to get the number of days in a month, you can alternatively use a for loop instead, eg:

    uses
      ..., DateUtils;
    
    var
      dtSelectedDate, dtStartDate, dtCurrentDate: TDateTime;
      iNumDays, I: Integer;
    begin
      dtSelectedDate := DateOf(CalendarView1.Date);
      iNumDays := DaysInMonth(dtSelectedDate);
      dtStartDate := StartOfTheMonth(dtSelectedDate);
    
      EditMonth.Text := IntToStr(iNumDays);
      EditStartDay.Text := DateToStr(dtStartDate);
      EditEndDay.Text := DateToStr(EndOfTheMonth(dtSelectedDate));
    
      dtCurrentDate := dtStartDate;
      for I := 1 to iNumDays do
      begin
        // insert dtCurrentDate into Table
    
        dtCurrentDate := dtCurrentDate + 1;
        // or:
        dtCurrentDate := IncDay(dtCurrentDate);
      end;
    end;