-5

I have a method Age() that returns the age of a car( subtracted from the year of production which is an int based on user input and it has to be an int).

Also, from this method I raise an event that shows me the age of the car. I only need the year, no months or days. My code is something like this and it's not working.The event is raised, but no value is shown. No errors in the code.

public int Age()
{

int Year= DateTime.Now.Year; // only the year in int

int YIP=Year-Year of production; // Year of production from user input

return YIP;

}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325

2 Answers2

1

You can use AddYears with a negative value for year:

var myNewDateMinusOneYear = Datetime.Today.AddYears(-1) 

Additional resources

DateTime.AddYears Method (Int32)

Returns a new DateTime that adds the specified number of years to the value of this instance.

Return Value Type: System.DateTime An object whose value is the sum of the date and time represented by this instance and the number of years represented by value.

Remarks This method does not change the value of this DateTime object. Instead, it returns a new DateTime object whose value is the result of this operation.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
0

Just use the below code, it should help you.

var previousYear = System.DateTime.Now.AddYears(-1);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364