I'm wondering how to compute the percentage between two DateTimes, I have a BackgroundWorker that executes until a provided DateTime is reached, that part is working fine, I just want to display in the UI what's the percentage completed of the worker.
I tried to use the following approach:
var now = DateTime.Now;
var executeUntil = DateTime.Now..AddHours(4).AddMinutes(10);
var percentage = (int)(( executeUntil.Ticks * 100 ) / now.Ticks );
but is always returning 1, i'm guessing that this is because Ticks is a long number and somehow is truncating the division.
Any suggestions?
Try this:
var start = DateTime.Now;
var end = DateTime.Now.AddMinutes(1);
var total = (end - start).TotalSeconds;
for( int i = 0; i < 10; i++)
{
Thread.Sleep(6000);
var percentage = (DateTime.Now - start).TotalSeconds*100/total;
Console.WriteLine(percentage);
}
You're correct about the truncation. Right now you're dividing by longs so the quotient is going to have Math.Floor
applied to it and also be a long that doesn't support decimals. To fix the exact code you gave you need to make either the divisor or the dividend a floating point number. This quickly makes the numerator a double.
var percentage = (int)(( executeUntil.Ticks * 100d ) / now.Ticks );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.