How to get the difference between two DateTime in hour with C# ?

I am currently developing a mobile app with Xamrin.Forms and I had to know the difference between two DateTime in hours. It seems dumb, but in fact, it is quite tough to find a smart and optimised way to do it. I wanted to share with you the solution I found.

Basics

First, let's look at the basics.

Picture of a computer with code on the screen.

Example

Here is a code snippet using this method to get the hour difference for training.

public int GetHourDifference(DateTime dateBefore, DateTime dateAfter)
{
  TimeSpan hourDifferenceSpan = dateAfter.Subtract(dateBefore);

  int hourDifference = hourDifferenceSpan.TotalHours;

  return hourDifference;
}

DateTime trainingBegin = DateTime.Today; // The training begins now
DateTime trainingEnd = DateTime.Today.AddHours(2);

Console.WriteLine("The training will last " + GerHourDifference(trainingBegin, trainingEnd) + " hours.");

Thank you so much for reading! I like to share all of those little tips! If you like it and it also interests you, please let me know in the comments! I can do these with JS, PHP, HTML and CSS. I will also try to create some little videos with tips like that. If you would like to see that, share it in the comments below. ✨

If you want to support me, you can always buy me a coffee.

Sources