Kai Kai - 5 months ago 22
C# Question

Calculation with DateTime and TimeSpan in C#

I need to make a calculation of passed and remaining time of an operation in C#.
I have the start of the operation saved in a string format of HH:MM:SS

I have a default time length of the operation in a string format of HH:MM:SS

Now I would like to calculate:


  • The remaining time / extra time: For example if the operation is still below the default length, it should display -HH:MM:SS, and if the operation took longer than the default time, it should display +HH:MM:SS

  • If the operation took longer, I would also like to have a double value of HH,MM in % style. For example: 3hours and 30 minutes should be displayed as 3,5



Both results to be displayed next to each other.
I know I have to translate the string values into DateTime and/or TimeSpan values to do calculations, but currently I have no idea how to calculate since the first operation for example would not give me a negative value, but just get back in time [22:30:00 of yesterday].

Answer Source

Try this..

var start = "17:05:11"; // Pass this as a parameter
var startTime = DateTime.Parse(start);

var defaultDuration = TimeSpan.FromMinutes(2);
TimeSpan operationDuration = startTime - DateTime.Now;

TimeSpan diff = defaultDuration - operationDuration;

if (operationDuration > defaultDuration)
{
    Console.Out.WriteLine($"+{diff.Hours}:{diff.Minutes}:{diff.Seconds}");
}
else
{
    Console.Out.WriteLine($"-{diff.Hours}:{diff.Minutes}:{diff.Seconds}");
    Console.Out.WriteLine($"{diff.Hours},{Math.Round(((double)(diff.Minutes * 100 / 60)),0, MidpointRounding.AwayFromZero)}");//example: 3hours and 30 minutes should be displayed as 3,5
}