Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract one month from Datetime.Today

Tags:

c#

.net

winforms

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; } 
like image 880
user3859356 Avatar asked Jan 05 '15 09:01

user3859356


People also ask

How do you subtract dates in Python?

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.


1 Answers

Just substract a month by 'adding` -1:

var lastmonth = DateTime.Today.AddMonths(-1); 

See the MSDN documentation on DateTime.AddMonths.

like image 189
Patrick Hofman Avatar answered Sep 20 '22 03:09

Patrick Hofman