How to convert fractional years (say 1.25 years) to number of days

半腔热情 提交于 2019-12-14 03:31:59

问题


I have a table that shows periods like 1 year to 10 years. I want to calculate number of days (approximately 365 days in a year and no need to include leap year). If it was just years, it is easy to calculate days ( like 2 years = 2*365 days). But how can convert for 1.5 years or 1.75 years into days?

what is the efficient way to calculate days if the years are specified in terms of fractional years.

Thanks nath


回答1:


Try:

float year = 1.5;

int days = Math.Round(year * 365);



回答2:


Since the original question is trivial, I'll answer the more interesting question where leap years and other date/time oddities are to be considered. Since the exact number of days in a year is dependent on the year in question, the only sensible approach would be to calculate it relative to a given date. The first step would be an AddYears overload that accepts double values:

public static DateTime AddYears(this DateTime dateTime, double years)
{
    int roundedYears = (int) Math.Floor(years);
    var roundedDate = dateTime.AddYears(roundedYears);
    var lastYearSpan = roundedDate.AddYears(1) - roundedDate;
    return roundedDate.AddDays((years % 1) * lastYearSpan.TotalDays);
}

Now you can get the number of days that make sense for you, for example:

var now = DateTime.UtcNow;
Console.WriteLine((now.AddYears(1.25) - now).TotalDays); 

Sample tests:

public void TestAddYearsDouble()
{
    var date = new DateTime(2000, 1, 15); //middle of the month to keep things simple
    Assert.AreEqual(date.Year + 1, date.AddYears(1.0).Year);
    Assert.AreEqual(date.Month, date.AddYears(1.0).Month);
    Assert.AreEqual(date.Year, date.AddYears(0.0833).Year);
    Assert.AreEqual(date.Month + 1, date.AddYears(0.0833).Month);
    Assert.AreEqual(date.Year + 8, date.AddYears(8.5).Year);
    Assert.AreEqual(date.Month + 6, date.AddYears(8.5).Month);
}


来源:https://stackoverflow.com/questions/14859332/how-to-convert-fractional-years-say-1-25-years-to-number-of-days

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!