Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't TDateTimePicker let me navigate to February?

I am using a TDateTimePicker on my D7 app with the following properties:

Format = 'MMM-yyyy'
DateMode = dmUpDown

When I try to set the current date time to it using dt1.DateTime := Now, it sets the time and date correctly, but it shows an exception when I try to navigate the months. In particular, I cannot circulate below the month of March.

What is causing this issue?

like image 479
CyprUS Avatar asked Jan 29 '13 13:01

CyprUS


1 Answers

The problem is that the date time picker control is being initialised with the current date. And that includes a day of the month that is invalid for some months.

So, just to be clear, you are asking this question on the 29th January 2013. When you click on the up/down control to move to February, the control fails to perform the change because there is no 29th February in 2013.

For any future visitors that find it hard to reproduce, this is the code you need to demonstrate the issue:

DateTimePicker1.Format := 'MMM-yyyy';
DateTimePicker1.DateMode := dmUpDown;
DateTimePicker1.DateTime := EncodeDateTime(2013, 1, 29, 0, 0, 0, 0);

The simple fix for the problem is to make sure that the DateTime property for the control is for the start of the month. You can achieve that by executing this code when you initialise the control:

DateTimePicker1.DateTime := StartOfTheMonth(DateTimePicker1.DateTime);

Or perhaps if you want to be more explicit:

DateTimePicker1.DateTime := StartOfTheMonth(Date);

The StartOfTheMonth helper function is found in the DateUtils unit.

like image 127
David Heffernan Avatar answered Oct 21 '22 06:10

David Heffernan