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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With