I need to calculate years and months from a given number. how can I do it? eg: I am giving: 26 I need to get result: 2 years 2months please help
Asked
Active
Viewed 192 times
-2
-
What did you tried? Its just simple you need to divide by 12... – Nikunj Kakadiya Feb 15 '21 at 04:36
1 Answers
1
Unless you have some more specific requirements, it should be as easy as Integer Division and the Remainder operator %
var input = 26;
var years = input / 12;
var months = input % 12;
Console.WriteLine($"{years} years and {months} months");
Output
2 years and 2 months
or
private static (int Years, int Months) GetYearsAndMonths(int input)
=> (input / 12, input % 12);
...
var result = GetYearsAndMonths(26);
Console.WriteLine($"{result.Years} years and {result.Months} months");
or the little known method Math.DivRem Method
as supplied by @Charlieface
Calculates the quotient of two numbers and also returns the remainder in an output parameter.

TheGeneral
- 79,002
- 9
- 103
- 141
-
-
@Charlieface updated and attributed. I have seen this so many times, and never had a use for it, until now! – TheGeneral Feb 15 '21 at 06:03
-
Mainly useful in very tight, high perf loops, because most processors can do this in a single instruction. – Charlieface Feb 15 '21 at 06:05