C# Date Diffs

Every time I have to write a DateDiff function in C# I always end up second guessing myself to make sure I’ve got the order of operations correct.

So this post is just for my future self when I inevitably end up needing to remember which order the DateTime subtractions should be in:

1
2
3
4
5
6
7
8
9
10
11
public class Program
{
public static void Main(string[] args)
{
var currentTime = DateTime.Parse("10/10/2010 5:05:00 AM");
var timeInTheFuture = DateTime.Parse("10/10/2010 5:10:00 AM");
var timeInThePast = DateTime.Parse("10/10/2010 5:00:00 AM");
Console.WriteLine((timeInTheFuture - currentTime).Minutes); // should be 5
Console.WriteLine((currentTime - timeInThePast).Minutes); // should be 5 as well
}
}

.NET Fiddle here: https://dotnetfiddle.net/Ten6J0