get full year difference between dates in csharp

To get the full year difference between two dates in C#, you can first calculate the time span between them using the TimeSpan structure. Then, you can divide the total number of days in the time span by 365.25 (the average number of days in a year) to get the full year difference.

Here's an example code snippet:

main.cs
DateTime date1 = new DateTime(2020, 1, 1);
DateTime date2 = new DateTime(2021, 6, 30);

TimeSpan timeSpan = date2 - date1;
int fullYears = (int)(timeSpan.TotalDays / 365.25);

Console.WriteLine("Full year difference: " + fullYears);
233 chars
8 lines

Output:

main.cs
Full year difference: 1
24 chars
2 lines

In this example, we calculate the full year difference between Jan 1, 2020 and June 30, 2021, which is 1 year.

gistlibby LogSnag