Work out minutes difference between dates

Sandeep Bansal picture Sandeep Bansal · Jul 13, 2011 · Viewed 23k times · Source

I have the following code:

DateTime pickerDate = Convert.ToDateTime(pickerWakeupDate.SelectedDate);
string enteredStr = pickerDate.ToShortDateString() + " " + textWakeupTime.Text;
string format = "dd/M/yyyy HH:mm";
DateTime enteredDate = DateTime.ParseExact(enteredStr, format, null);

The problem I am facing is that I would like to workout the difference between the set date and the date and time now. This value will then need to provide me a value of how many minutes there are between the dates.

I tried using:

DateTime todaysDateTime = DateTime.Now;
TimeSpan span = enteredDate.Subtract(todaysDateTime);
int totalMins = span.Minutes;

But this gave me an incorrect value 0 when the value was set 10 minutes ahead.

Can anyone help me solve this

Thanks.

Answer

Jamiec picture Jamiec · Jul 13, 2011

i think what you really want is span.TotalMinutes (I cant tell you how many times this has caught me out on the TimeSpan class!)

For reference

TimeSpan.Minutes - "Gets the minutes component of the time interval represented by the current TimeSpan structure."

TimeSpan.TotalMinutes - "Gets the value of the current TimeSpan structure expressed in whole and fractional minutes."