How do I get the time difference between two DateTime objects using C#?

The following example demonstrates how to do this:

DateTime a = new DateTime(2010, 05, 12, 13, 15, 00);
DateTime b = new DateTime(2010, 05, 12, 13, 45, 00);
Console.WriteLine(b.Subtract(a).TotalMinutes);

When executed this prints “30” since there is a 30 minute difference between the date/times.

The result of DateTime.Subtract(DateTime x) is a TimeSpan Object which gives other useful properties.

Leave a Comment