Search code examples
vb.netwinformsdatetimedatetimepickermonthcalendar

DateTimePicker only for current Month


I have a DateTimePicker in a Form. I need to restrict the user to only select a Date from the current Month: for example, from 1 November 2018 to 30 November 2018.

I tried these lines of code:

DtpIssue.MinDate = New Date Time(DateTime.Now.Year, DateTime.Now.Month, 1)
DtpIssue.MaxDate = New Date Time(DateTime.Now.Year, DateTime.Now.Month, 1)

But it shows only the current date: 10 November 2018. What should I do to fix the current Month for the DateTimePicker?


Solution

  • The last day of the month is returned by DateTime.DaysInMonth(), passing the current Year and Month.

    Dim FirstOfMonth As Date = New DateTime(Date.Now.Year, Date.Now.Month, 1)
    Dim EndOfMonth As Date = 
        New DateTime(Date.Now.Year, Date.Now.Month, Date.DaysInMonth(Date.Now.Year, Date.Now.Month))
    

    In a similar format, applied to your controls:

    DtpIssue.MinDate = New Date(Today.Year, Today.Month, 1)
    DtpIssue.MaxDate = New Date(Today.Year, Today.Month, Date.DaysInMonth(Today.Year, Today.Month))