0

I am calculating the difference between dateTimePicker2 and dateTimePicker1 and converting it to minutes as this,

durinmin = Convert.ToInt32((dateTimePicker2.Value - dateTimePicker1.Value).TotalMinutes);

Problem is, for example if the difference value is "00:17:40", the durinmin = 18. But I want to hold the value of only completed minutes, i.e., durinmin=17 is the value I want my program to consider. How to get it?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Vasanth
  • 43
  • 1
  • 11
  • 1
    I wouldn't expect that behaviour. Please post a short but complete example - noting that `DateTimePicker.Value` just returns a `DateTime`, so you can easily write a [mcve] which *doesn't* use `DateTimePicker`, and just hard-codes two `DateTime` values. (Console apps make for great short examples...) – Jon Skeet Dec 23 '15 at 08:27
  • 1
    Please refer to this similar thread: http://stackoverflow.com/questions/1393696/rounding-datetime-objects Regards. – El maik Dec 23 '15 at 08:38
  • Interesting close-vote: _Off topic, not about programming_. Ehh..? – Gustav Dec 23 '15 at 10:00

3 Answers3

7

Having said that I wouldn't expect that behaviour, I've just noticed that Convert.ToInt32 rounds instead of truncating - so it's behaving exactly as expected. The TotalMinutes property is returning 17.6666 (etc) which is being rounded up to 18.

All you need to do is use a cast instead of the method - casting to int will truncate towards 0:

TimeSpan difference = dateTimePicker2.Value - dateTimePicker1.Value;
int minutes = (int) difference.TotalMinutes;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

just use Math.Floor

durinmin = (int)Math.Floor((dateTimePicker2.Value - dateTimePicker1.Value).TotalMinutes);
slawekwin
  • 6,270
  • 1
  • 44
  • 57
  • 3
    You don't need to use `Math.Floor` - just casting is enough. One difference here is that if the duration is *negative*, this will round down instead of rounding towards 0. It's not entirely clear what the OP would want in this case... – Jon Skeet Dec 23 '15 at 08:30
  • It's impossible to get negative duration in this case. coz, durinmin = (stop time - start time). But it's good to have your valuable suggestion. – Vasanth Dec 23 '15 at 09:00
  • Jon's answer is probably better as per above comment – slawekwin Dec 23 '15 at 09:00
1

Instead of using TotalMinutes, use the Minutes property of the TimeSpan:

durinmin = Convert.ToInt32((dateTimePicker2.Value - dateTimePicker1.Value).Minutes);