关于c#:如何计算两个日期之间的年数?


How to calculate the number of years between 2 dates?

我想比较两个日期,以确认这两个日期之间的年数是>= 18。例如,如果我的2个日期是03-12-201103-12-1983,那么这应该通过验证,但是,如果我的2个日期是03-12-201103-12-1995,那么这应该失败验证。

有人能帮我吗?


希望你是什么looking for this isP></

1
2
3
4
public bool CheckDate(DateTime date1, DateTime date2)
{
    return date1.AddYears(-18) < date2;
}


你的问题-王辗转title description &;让它在更多的空闲位。我从你从你gathered looking for original后安年龄验证功能。这里就是会给你:P></

1
2
3
4
5
6
7
8
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;
}


使用TimeSpan构。P></

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


1
2
3
4
5
6
7
8
9
10
11
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);

参考链接P></


如果是在method to check is the年龄超过18:P></

1
2
3
4
5
6
    private bool IsMoreThan18(DateTime from, DateTime to)
    {
        int age = to.Year - from.Year;
        if (from > to.AddYears(-age)) age--;
        return age >= 18;
    }

用途:timespanP></

1
2
3
4
5
6
7
TimeSpan day = 03-12-2011 - 03-12-1983;
                double year = day.TotalDays / 365.25;

                if (year > 18)
                {

                }

也许instead of You should 2011 - 12 - 03现在使用的日期时间。P></


结构:timespan check themsdn.microsoft.com http:/ / / / / system.timespan.aspx恩-美国图书馆P></


两个DateTime对象创建和衬底eachother them from。the result is a aswel DateTime对象:P></

1
2
3
DateTime dt = new DateTime(2011, 12, 03);
DateTime dt2 = new DateTime(1983, 12, 03);
DateTime dt3 = dt - dt2;

现在你可以检查dt3.Year年between them for the number ofP></