Search code examples
c#winformsdatetimepicker

How can I limit the DateTimePicker to only change the date, not the time?


Here's the situation:

I have two DateTimePicker controls for the start date and end date in a log viewer. I want the start date to be whatever the user picks, but with a time of 00:00:00. The end time to be the date the user picks, but a time of 23:59:59.999.

(I'll also be writing code the ensure the end date is equal to or greater than the start date, but I can handle that)

What is the best way to implement this?


Solution

  • Just ignore the time part of the date you get from DTP with DateTime.Date. Like this:

        private void btnOK_Click(object sender, EventArgs e) {
            var start = dtpStart.Value.Date;
            var end = dtpEnd.Value.Date.AddDays(1).AddMilliseconds(-1);
            if (end > start) {
                // etc...
            }
        }