13

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!

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
P Sawicki
  • 189
  • 1
  • 2
  • 9
  • The result is not guaranteed to be 1. It might be 1, it might be greater. `Sleep` only guarantees that no work will be done for `n` milliseconds, not that work will resume in `n` milliseconds. Don't be surprised if your result is incorrect at times. – Kenneth K. Jul 18 '17 at 13:21
  • You should *not* use `DateTime.Now` to measure the performance of code. Use a `System.Diagnostics.Stopwatch`. Please read [Five Common Daylight Saving Time Antipatterns of .NET Developers](http://codeofmatt.com/2015/03/06/common-daylight-saving-time-mistakes-for-net-developers/) – Matt Johnson-Pint Jul 18 '17 at 15:34

4 Answers4

40

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

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
7

I think a more elegant way of doing it would be by using the Stopwatch-Class

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
Xzibitee
  • 149
  • 4
3

Simply take the difference (and maybe round it if you want):

double preciseDifference = (end - start).TotalMinutes;
int differentMinutes = (int)preciseDifference;
René Vogt
  • 43,056
  • 14
  • 77
  • 99
1

Use TimeSpan.

It represents a time interval and will give you the difference that you're looking for.

Here's an example.

TimeSpan span = end.Subtract ( start );

Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
Ortund
  • 8,095
  • 18
  • 71
  • 139
meta4
  • 788
  • 1
  • 10
  • 24