Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate days in years and months?

Tags:

c#

calendar

How to calculate days in years and months in c#? per example :

If 1. days = 385 then I need to display Year= 1.1 (i.e. 1 year 1 month) 2. days= 234 then I need to display year =0.7 (i.e 0 year 7 months)

How can we calculate in c#?

I did for days=234 /365 and result is coming 0.64 (i.e. 0 year 6 months). But actually it is 7 months.

How to get accurate year and months.

like image 962
James123 Avatar asked Dec 05 '25 20:12

James123


1 Answers

You can do:

double temp  = (234.0 /365.0) * 12.0;

int years = (int)temp;
int months = (int)(temp - years);

This is because you were getting 0.64, which is 0.64 years. If you want months, you'd need to multiply that times 12.

In the above, you'll get 0 years and 7 months... That being said, I'm not sure exactly how you want to format this:

string yearsString = string.Format("{0}.{1}", years, months);

Just be aware that this will do 3.11 for 11 months, which is going to be odd, though it was your requirement.

Also, if you want to have this be very general, you might want to use 365.25 instead of 365 to represent a single Julian Year, as it will help you reduce issues due to leap years.

like image 120
Reed Copsey Avatar answered Dec 08 '25 12:12

Reed Copsey