Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created April 3, 2024 12:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karenpayneoregon/b395b7d8de0c4422787892e912f62891 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/b395b7d8de0c4422787892e912f62891 to your computer and use it in GitHub Desktop.

Shows how to get a person's age in years.

Below are two dates, current today's date, birthDate date of a person's birth.

int current = 20240403;
int birthDate = 19000924;

Format for both yyyyMMdd

Subtract current from birthDate, remove the last four characters to get years old.

int yearsOld = int.Parse((current - birthDate).ToString()[..^4]);

Variations

1️⃣

Console.WriteLine(
    (current - birthDate).ToString()
    .RemoveLastCharacters()
    .Age());

2️⃣

int now = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
int dob = int.Parse(new DateOnly(1900,9,24).ToString("yyyyMMdd"));
int age = (now - dob) / 10000;
Console.WriteLine(age);

3️⃣

Console.WriteLine(new DateOnly(1900, 9, 24).GetAge());
static void Main(string[] args)
{
int current = 20240403;
int birthDate = 19000924;
Console.WriteLine((current - birthDate).ToString()[..^4]);
Console.WriteLine((current - birthDate).ToString().RemoveLastCharacters());
int now = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
int dob = int.Parse(new DateOnly(1900,9,24).ToString("yyyyMMdd"));
int age = (now - dob) / 10000;
Console.WriteLine(age);
Console.WriteLine(new DateOnly(1900, 9, 24).GetAge());
}
public static class SomeExtensions
{
public static int GetAge(this DateOnly dateOfBirth)
{
var today = DateTime.Today;
var value1 = (today.Year * 100 + today.Month) * 100 + today.Day;
var value2 = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day;
return (value1 - value2) / 10000;
}
public static string RemoveLastCharacters(this string sender, int count = 4)
=> sender[..^count];
public static int Age(this string sender) => int.Parse(sender);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment