I have a DateTimePicker
in which I allow user to select month previous to the current year.
The problem is, that if the date is 1st January, it can't calculate the December month of last year in the way I am doing it now.
var today = DateTime.Today; var lastmonth = new DateTime(today.Year, today.Month - 1, 1); if (qs == "") { dateTimePicker1.MaxDate = lastmonth; dateTimePicker1.Value = lastmonth; } else { DateTime dt = Convert.ToDateTime(qs); dateTimePicker1.Value = dt; dateTimePicker1.MaxDate = lastmonth; }
Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1. A result is a timedelta object.
Just substract a month by 'adding` -1:
var lastmonth = DateTime.Today.AddMonths(-1);
See the MSDN documentation on DateTime.AddMonths
.
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