使用C#计算年份差异

106

我该如何计算两个日期之间的年份差异?

例如:(Datetime.Now.Today() - 11/03/2007) 的年份差异。


1
你标记为答案的代码实际上是错误的。它可能会返回不正确的结果。 - Mick
18个回答

2
    public string GetAgeText(DateTime birthDate)
    {
        const double ApproxDaysPerMonth = 30.4375;
        const double ApproxDaysPerYear = 365.25;

        int iDays = (DateTime.Now - birthDate).Days;

        int iYear = (int)(iDays / ApproxDaysPerYear);
        iDays -= (int)(iYear * ApproxDaysPerYear);

        int iMonths = (int)(iDays / ApproxDaysPerMonth);
        iDays -= (int)(iMonths * ApproxDaysPerMonth);

        return string.Format("{0} år, {1} måneder, {2} dage", iYear, iMonths, iDays);
    }

0
如果你正在处理月份和年份,你需要一个知道每个月有多少天以及哪些年份是闰年的东西。
这就是公历(以及其他特定文化的日历实现)的用处。
虽然日历不提供直接计算两个时间点之间差异的方法,但它确实有一些方法,例如:
DateTime AddWeeks(DateTime time, int weeks)
DateTime AddMonths(DateTime time, int months)
DateTime AddYears(DateTime time, int years)

0
DateTime musteriDogum = new DateTime(dogumYil, dogumAy, dogumGun);

int additionalDays = ((DateTime.Now.Year - dogumYil) / 4); //Count of the years with 366 days

int extraDays = additionalDays + ((DateTime.Now.Year % 4 == 0 || musteriDogum.Year % 4 == 0) ? 1 : 0); //We add 1 if this year or year inserted has 366 days

int yearsOld = ((DateTime.Now - musteriDogum).Days - extraDays ) / 365; // Now we extract these extra days from total days and we can divide to 365

0

这是计算年份和月份差异的最佳代码:

DateTime firstDate = DateTime.Parse("1/31/2019");
DateTime secondDate = DateTime.Parse("2/1/2016");

int totalYears = firstDate.Year - secondDate.Year;
int totalMonths = 0;

if (firstDate.Month > secondDate.Month)
    totalMonths = firstDate.Month - secondDate.Month;
else if (firstDate.Month < secondDate.Month)
{
    totalYears -= 1;
    int monthDifference = secondDate.Month - firstDate.Month;
    totalMonths = 12 - monthDifference;
}

if ((firstDate.Day - secondDate.Day) == 30)
{
    totalMonths += 1;
    if (totalMonths % 12 == 0)
    {
        totalYears += 1;
        totalMonths = 0;
    }
}

0

简单的解决方案:

public int getYearDiff(DateTime startDate, DateTime endDate){
    int y = Year(endDate) - Year(startDate);
    int startMonth = Month(startDate);
    int endMonth = Month(endDate);
    if (endMonth < startMonth) 
        return y - 1;
    if (endMonth > startMonth) 
        return y;
    return (Day(endDate) < Day(startDate) ? y - 1 : y);
}

0

运行完美:

    internal static int GetDifferenceInYears(DateTime startDate)
    {
        int finalResult = 0;

        const int DaysInYear = 365;

        DateTime endDate = DateTime.Now;

        TimeSpan timeSpan = endDate - startDate;

        if (timeSpan.TotalDays > 365)
        {
            finalResult = (int)Math.Round((timeSpan.TotalDays / DaysInYear), MidpointRounding.ToEven);
        }

        return finalResult;
    }

-1
也许这对回答问题有帮助:给定年份的天数计数
new DateTime(anyDate.Year, 12, 31).DayOfYear //will include leap years too

关于DateTime.DayOfYear Property的问题。

-1
以下是基于 Dana 的简单代码的改进版本,它在大多数情况下可以产生正确的答案。但它没有考虑到日期之间少于一年的情况。因此,这里是我使用的代码,以产生一致的结果:
public static int DateDiffYears(DateTime startDate, DateTime endDate)
{
    var yr = endDate.Year - startDate.Year - 1 +
             (endDate.Month >= startDate.Month && endDate.Day >= startDate.Day ? 1 : 0);
    return yr < 0 ? 0 : yr;
}

这也展示了@davomcdavo答案的闰年行为。 - Whelkaholism
你不能用 endDate.Month >= startDate.Month && endDate.Day >= startDate.Day 替换 (end.Month > start.Month) || ((end.Month == start.Month) && (end.Day >= start.Day)) - Jon Hallin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接