Tak to wygląda w klasie DataTime.. Wiek w liczbie dni.
Wiek w miesiącach to trochę głupie zadanie. Miesiące mają różną liczbę dni i nie wiem jak liczyć rozpoczęty albo niezakończony miesiąc
using System;
using System.Diagnostics.Contracts;
namespace ConsoleApp29
{
class Program
{
static void Main(string[] args)
{
DateTime dataUrodzenia = new DateTime(1980, 03, 20);
DateTime dataDzisiejsza = DateTime.Now;
Console.WriteLine("{0:%d}",dataDzisiejsza - dataUrodzenia);
long tick = (DateToTicks(2020,04, 21) - DateToTicks(1980, 03, 20));
tick /= 10000000;
tick /= 60;
tick /= 60;
tick /= 24;
Console.WriteLine(tick);
}
private static readonly int[] DaysToMonth366 = {
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};
private static readonly int[] DaysToMonth365 = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
private const long TicksPerMillisecond = 10000;
private const long TicksPerSecond = TicksPerMillisecond * 1000;
private const long TicksPerMinute = TicksPerSecond * 60;
private const long TicksPerHour = TicksPerMinute * 60;
private const long TicksPerDay = TicksPerHour * 24;
private static long DateToTicks(int year, int month, int day)
{
if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
{
int[] days = IsLeapYear(year) ? DaysToMonth366 : DaysToMonth365;
if (day >= 1 && day <= days[month] - days[month - 1])
{
int y = year - 1;
int n = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
return n * TicksPerDay;
}
}
throw new ArgumentOutOfRangeException(null);
}
public static bool IsLeapYear(int year)
{
if (year < 1 || year > 9999)
{
throw new ArgumentOutOfRangeException("year");
}
Contract.EndContractBlock();
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
}
}