How to convert fractional years (say 1.25 years) t

2019-09-29 09:19发布

问题:

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);
}


标签: c#-3.0