Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient method of finding a percentage of time

Tags:

c#

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?

like image 693
Mike Baxter Avatar asked Mar 26 '13 13:03

Mike Baxter


1 Answers

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;
    }
}
like image 192
Jon Skeet Avatar answered Oct 21 '22 07:10

Jon Skeet