I have set standard VCL TDateTimePicker
- MaxDate
property to Date
- e.g.
DTPicker.MaxDate := Date;
However, there is a problem. If I now set the date to be the current one:
DTPicker.Date := Date;
It will not accept it. The control simply stays at the date which is set at the design time. I can solve it by setting MaxDate to be Date + 1
and then setting the Date
property works fine and shows today's date, but then user is able to select tomorrow's date. I also tried to set MaxDate
to Date + 0.99999999
but that also is of no help.
I use Delphi 2010 and C++Builder 2010 (if this is a bug in either of them).
Any ideas how to prevent selecting any date beyond today and set the control date to today's date?
Changing the date results in - "Failed to set calendar date or time."
Update:
I managed to make it work as following:
My solution will likely be to use range-check before closing the form, as it seems that MaxDate
is useless, at least with this version of Delphi.
It appears it's the time portion of Date
that's causing the problem. This works fine on D2007, XE, XE8, and Delphi 10 Seattle:
DateTimePicker1.MaxDate := Trunc(Date) + 0.99999999999;
DateTimePicker1.Date := Date;
Tested using a brand new VCL forms application. Drop a TDateTimePicker
and a TButton
on the form, and generate an event for the FormCreate
for the form:
procedure TForm1.FormCreate(Sender: TObject);
begin
DateTimePicker1.MaxDate := Trunc(Date) + 0.99999999999;
end;
and the button:
procedure TForm1.Button1Click(Sender: TObject);
begin
DateTimePicker1.Date := Date;
end;
Run the app, click the DateTimePicker combobox to display the calendar, and pick any date that's available. The DateTimePicker displays the selected date. Click the button, and the DateTimePicker updates to show today's date. Dropping down the calendar again shows the correct dates available.
Of course, as Remy Lebeau pointed out in a comment: in an actual application, you wouldn't want to hard-code the time portion. A better solution would be to use DateUtils.EndOfDay(Date)
or Trunc(Date) + EncodeTime(23, 59, 59, 999)
.