Link to home
Start Free TrialLog in
Avatar of Adnan
AdnanFlag for Norway

asked on

How to calculate year and month out of int value....

Hi

How can i calculate year /month out of int value,  if i have a value "16", that means it is 1 year and 4 months.
Whatever result i get in int iw ant it to be calculated in year and months

How can i do that?

 var currDate = DateTime.Now.ToShortDateString();

                    DateTime.TryParseExact(ansiennitetsdatoberegnet, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out startDate);
                    DateTime.TryParseExact(currDate, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out currentDate);

                    result = ((startDate.Year - currentDate.Year) * 12) + startDate.Month - currentDate.Month;
                    var result2 = 12 * (startDate.Year - currentDate.Year) + startDate.Month - currentDate.Month;
                    var res = Math.Abs(result); //res returns 16 ,  1 year, 4 months......

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Jeff Edmunds
Jeff Edmunds
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Norie
Norie

Perhaps
var yrs = res/12;
    
var mths = res % 12;

Console.WriteLine (string.Format("{0} years {1} months", yrs,mths));

Open in new window

Avatar of Adnan

ASKER

Thanks, solved my issue, but why using Int64 and not just Int?
You could really use either.  With numbers that small, "int" or "Int32" probably makes more sense. It was more just to show the code using an integer value.