Home > Mobile >  How to Calculate with TimeSpan in c#
How to Calculate with TimeSpan in c#

Time:09-22

I need to divide two TimeSpan.

I have one TimeSpan "worktime" and the other TimeSpan "productive"

What i want is to get as result of worktime/productive is a percentage. I need to get the "added value" (<- I think this is how it's called in english :)),

CodePudding user response:

In .NET Core you can simply divide the TimeSpans. TimeSpan has a division operator.

This works:

var t1=TimeSpan.FromTicks(1000);
var t2=TimeSpan.FromTicks(100);
Console.WriteLine(t2/t1);
---------------------
 0.1                                                                                                                  ```

CodePudding user response:

A Simple example:

DateTime d1 = DateTime.Parse("10:00:00");
DateTime d2 = DateTime.Parse("13:00:00");
TimeSpan t1 = d2 - d1;                    //   three hours
TimeSpan t2 = new TimeSpan(0,15,0);       //   15 minutes
Console.WriteLine(t1/t2);

This outputs: 12

see: https://onlinegdb.com/ImxwiWk37

CodePudding user response:

var addedValue = (decimal)workTime.Ticks/productive.Ticks * 100;

The decimal cast is needed or the division will automatically round and you'll get very inaccurate percentages in certain cases.

CodePudding user response:

I need to get the "added value"

By this, do you mean you want the percentage expressed as a percentage of the overall work time that was productive?

So if the total work time was 10 hours and the productive work time was 9 hours, the percentage of productive work time would be 90%?

If so, the answer is:

double percentage = double percentage = 100.0 - 100.0 * (worktime.Ticks - productive.Ticks) / worktime.Ticks;
  • Related