Is there an efficient method of calculating the percentage of X from Y, when both data types are TimeSpan
?
Eg, a basic question would be that 1:00:00
is 50% of 2:00:00
.
What would be an effective method of calculating what percentage is 00:34:23
of 4:12:31
?
EDIT: As per the comment, the types really are intended to be TimeSpan
rather than DateTime
, at which point everything is simple.
When you ask what proportion X is of Y, that's basically division, which is easily implemented on TimeSpan
:
public static double Divide(TimeSpan dividend, TimeSpan divisor)
{
return (double) dividend.Ticks / (double) divisor.Ticks;
}
Sample code:
using System;
using System.IO;
using System.Globalization;
using System.Linq;
class Test
{
static void Main()
{
TimeSpan x = new TimeSpan(0, 34, 23);
TimeSpan y = new TimeSpan(4, 12, 31);
Console.WriteLine(Divide(x, y)); // 0.13616 etc, i.e. 13%
}
public static double Divide(TimeSpan dividend, TimeSpan divisor)
{
return (double) dividend.Ticks / (double) divisor.Ticks;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With