C# - Calculating time difference in minutes

P Sawicki picture P Sawicki · Jul 18, 2017 · Viewed 13.8k times · Source

I have got the following code:

DateTime start = DateTime.Now;
Thread.Sleep(60000);
DateTime end = DateTime.Now;

and I would like to calculate the difference in minutes between start and end. How am I supposed to do it? For the example above, the result should be '1'.

Thanks in advance!

Answer

Mighty Badaboom picture Mighty Badaboom · Jul 18, 2017

You could use the Subtract method and using TotalMinutes.

var result = end.Subtract(start).TotalMinutes;

If you need it without fractional minutes just cast it as an int.

var result = (int)end.Subtract(start).TotalMinutes;

Have a look at the MSDN for further information: Substract and TotalMinutes