Vasanth
Vasanth

Reputation: 43

Round off dateTimePicker value

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?

Upvotes: 0

Views: 298

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500515

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;

Upvotes: 7

user4761639
user4761639

Reputation:

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

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

Upvotes: 1

slawekwin
slawekwin

Reputation: 6310

just use Math.Floor

durinmin = (int)Math.Floor((dateTimePicker2.Value - dateTimePicker1.Value).TotalMinutes);

Upvotes: 1

Related Questions