Skip to content

Instantly share code, notes, and snippets.

@solrevdev
Created July 20, 2023 09:06
Show Gist options
  • Save solrevdev/d26a1e3f1ef8d264256a80e4308def3e to your computer and use it in GitHub Desktop.
Save solrevdev/d26a1e3f1ef8d264256a80e4308def3e to your computer and use it in GitHub Desktop.
Using DateOnly and Record's is C# to work out how old someone is
using System;
Console.WriteLine("No static void main");
var p = new Person(Guid.NewGuid(), "John", new DateOnly(1975, 1, 1));
Console.WriteLine(p.ToString());
public record Person(Guid Id, string Name, DateOnly DateOfBirth)
{
public override string ToString()
{
var currentDate = DateOnly.FromDateTime(DateTime.Today);
var age = currentDate.Year - DateOfBirth.Year;
var months = currentDate.Month - DateOfBirth.Month;
if (currentDate.Day < DateOfBirth.Day)
months--;
if (months < 0)
{
age--;
months += 12;
}
return $"{Name} is {age} years and {months} months old";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment