An effective method of finding the percentage of time

Is there an efficient method to calculate the percentage of X from Y when both data types TimeSpan?

For example, the main question is what 1:00:00is 50% of 2:00:00. What would be an effective method of calculating what percentage 00:34:23 4:12:31?

+5
source share
3 answers

EDIT: according to the comment, the types really should be TimeSpan, not DateTime, and at that moment everything is simple.

When you ask what proportion of X belongs to Y, this is the main division, which is easily implemented on TimeSpan:

public static double Divide(TimeSpan dividend, TimeSpan divisor)
{
    return (double) dividend.Ticks / (double) divisor.Ticks;
}

Code example:

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;
    }
}
+9
source

DateTime.Ticks. , DateTime Ticks eachother. .

, TimeSpan, DateTime.

+7

Time is measured in units, and any time can be converted into a number of these units, and then processed like any other number. Create TimeSpanand take TotalSeconds, and then do the math.

+2
source

All Articles