C# 如何计算两个日期之间的年数?

C# 如何计算两个日期之间的年数?,c#,C#,我想比较两个日期,以确认两个日期之间的年数为=18。例如,如果我的两个日期是03-12-2011和03-12-1983,则应通过验证,但是,如果我的两个日期是03-12-2011和03-12-1995,则验证应失败 有人能帮我吗?检查时间跨度结构: 使用TimeSpan结构 TimeSpan span= dateSecond - dateFirst; int days=span.Days; //or int years = (int) (span.Days / 365.25); 希望这就是你要

我想比较两个日期,以确认两个日期之间的年数为
=18
。例如,如果我的两个日期是
03-12-2011
03-12-1983
,则应通过验证,但是,如果我的两个日期是
03-12-2011
03-12-1995
,则验证应失败


有人能帮我吗?

检查时间跨度结构:

使用
TimeSpan
结构

TimeSpan span= dateSecond - dateFirst;
int days=span.Days;
//or
int years = (int) (span.Days / 365.25);

希望这就是你要找的

public bool CheckDate(DateTime date1, DateTime date2)
{
    return date1.AddYears(-18) < date2;
}
public bool CheckDate(日期时间日期1,日期时间日期2)
{
返回日期1.添加年份(-18)<日期2;
}

创建两个DateTime对象,并将它们相互减去。 结果也是一个DateTime对象:

DateTime dt = new DateTime(2011, 12, 03);
DateTime dt2 = new DateTime(1983, 12, 03);
DateTime dt3 = dt - dt2;
现在,您可以查看
dt3.Year
,了解它们之间的年数

使用时间跨度:

TimeSpan day = 03-12-2011 - 03-12-1983;
                double year = day.TotalDays / 365.25;

                if (year > 18)
                {

                }

也许你不应该使用2011年12月3日,而应该使用DateTime。现在,我重新调整了你的问题标题和描述,让它更清楚一点。从我从你的原始帖子中收集到的信息来看,你正在寻找年龄验证功能。下面是我要做的:

function VerifyAge(DateTime dateOfBirth)
{
    DateTime now = DateTime.Today; 
    int age = now.Year - dateOfBirth.Year;
    if (now.Month < dateOfBirth.Month || (now.Month == dateOfBirth.Month && now.Day < dateOfBirth.Day)) 
        age--;
    return age >= 18; 
}
函数验证年龄(DateTime-dateOfBirth)
{
DateTime now=DateTime.Today;
int age=now.Year-dateof birth.Year;
if(now.Month=18岁;
}

以下是检查年龄是否超过18岁的方法:

    private bool IsMoreThan18(DateTime from, DateTime to)
    {
        int age = to.Year - from.Year;
        if (from > to.AddYears(-age)) age--;
        return age >= 18;
    }

reference

OP查找的是年,而不是天
DateTime
类有几种简便的方法,您尝试过吗?OP查找的是年,而不是天。他应该用AddYears代替。你不是说TimeSpan dt3吗?
TimeSpan
没有年份属性。
DateTime zeroTime = new DateTime(1, 1, 1);

DateTime a = new DateTime(2008, 1, 1);
DateTime b = new DateTime(2016, 1, 1);

TimeSpan span = b - a;
// because we start at year 1 for the Gregorian 
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1; 

Console.WriteLine("Years elapsed: " + years);