给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?


当前回答

一句话的回答:

DateTime dateOfBirth = Convert.ToDateTime("01/16/1990");
var age = ((DateTime.Now - dateOfBirth).Days) / 365;

其他回答

不知道为什么没有人尝试过:

        ushort age = (ushort)DateAndTime.DateDiff(DateInterval.Year, DateTime.Now.Date, birthdate);

它只需要使用Microsoft.VisualBasic;并引用项目中的此程序集(如果尚未引用)。

我对DateTime一无所知,但我能做的就是:

using System;
                    
public class Program
{
    public static int getAge(int month, int day, int year) {
        DateTime today = DateTime.Today;
        int currentDay = today.Day;
        int currentYear = today.Year;
        int currentMonth = today.Month;
        int age = 0;
        if (currentMonth < month) {
            age -= 1;
        } else if (currentMonth == month) {
            if (currentDay < day) {
                age -= 1;
            }
        }
        currentYear -= year;
        age += currentYear;
        return age;
    }
    public static void Main()
    {
        int ageInYears = getAge(8, 10, 2007);
        Console.WriteLine(ageInYears);
    }
}

有点困惑,但仔细看代码,这一切都是有意义的。

这是一个非常简单的方法:

int Age = DateTime.Today.Year - new DateTime(2000, 1, 1).Year;

以下是使用DateTimeOffset和手动数学的答案:

var diff = DateTimeOffset.Now - dateOfBirth;
var sinceEpoch = DateTimeOffset.UnixEpoch + diff;

return sinceEpoch.Year - 1970;
        var EndDate = new DateTime(2022, 4, 21);

        var StartDate = new DateTime(1986, 4, 25);

        Int32 Months = EndDate.Month - StartDate.Month;

        Int32 Years = EndDate.Year - StartDate.Year;

        Int32 Days = EndDate.Day - StartDate.Day;

        if (Days < 0)
        {
            Months = Months - 1;
        }

        if (Months < 0)
        {
            Years = Years - 1;

            Months = Months + 12;
        }
        
        string Ages = Years.ToString() + " Year(s) " + Months.ToString() + " Month(s) ";