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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With