开发者

How do I calculate difference in years and months given a start and end [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Calculate Years, Months, weeks and Days

How do I calculate difference in years and months given a start and end date?

Hi

Working on a c# 2.0 project and I need to calculate the difference in years and months given the start and end date

I was thinking of a function like

        public void CalculateYearsAndMonths(DateTime startDate,
                                            DateTime endDate,
                                            out int years,
                                  开发者_如何学Go          out int months)
        {
            int years=0;
            int months=0;

            //????
        }

any suggestions?


This code works even when number of days between two dates are 365 days. E.g. 29th February 1972 and 28. February 1973, then it will return 0 years and 11 months.

if (endDate < startDate)
{
    DateTime temp = endDate;
    endDate = startDate;
    startDate = temp;
}

years = endDate.Year - startDate.Year;
months = endDate.Month - startDate.Month;
int days = endDate.Day - startDate.Day;
if (days < 0) months--;
if (months < 0)
{
    months += 12;
    years--;
}

By the way, you need to remove the two lines to make the out parameters work correctly:

int years=0;
int months=0;


I think the number of the months is ambiguous as each month get the different number of days. However, if based on DateTime.MinValue, you can use like:

        TimeSpan difference = endDate - startDate;

        DateTime age = DateTime.MinValue + difference;

        // Min value is 01/01/0001

        int ageInYears = age.Year - 1;
        int ageInMonths = age.Month - 1;
        int ageInDays = age.Day - 1;

        Console.WriteLine("{0}, {1}, {2}", ageInYears, ageInMonths, ageInDays); 


This depends on how you want to count months and years. Do you care about boundaries crossed (e.g. Jan 25 to Feb 1 = one month OR Dec 30 to Jan 1 = 1 year) or about the number of average size months/years (e.g. 29 days in month or 365 days in year) between two dates?

The TimeSpan result you can get by subtracting dates will give you all the fixed size time periods (e.g. days, minutes)

See this question for some details around why months and years can be hard.


int years = endDate.Year - startDate.Year;
int months = endDate.Month - startDate.Month;

You can try the above, should work.


Something like this?

        var end = endDate.Year + endDate.Month / 12.0;
        var start = startDate.Year + startDate.Month / 12.0;

        var years = (int)(end - start);
        var months = (end - start) * 12;

Not sure if you wanted to round the months...

Hope this helps,

John

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜