Created
July 20, 2023 09:06
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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