Search code examples
c#string-formattingfunclivecharts

Calculating time using modulus with possible rounding errors


I receive a time value in seconds from a database and I want to calculate this to a readable time. These are total active times for messages, so I don't have to take any leap years into account.

I'm calculating times from seconds that can be over 24 hours so hhh:mm:ss. I use this to format the lables on a chart from Live Charts. In my code I use the following code to calculate it:

public Func<double, string> Formatter { get; set; }

Formatter = value => (((value - (value % 3600)) / 3600) + ":" + (((value % 3600) - (value % 60)) / 60) + ":" + (value % 60));

This works fine but sometimes results in:

222:3:4

but what I want is:

222:03:04

I've found the following code to make a string.Format but I don't know how I can apply this when I'm using Func<>:

static string Method1(int secs)
{
    int hours = secs / 3600;
    int mins = (secs % 3600) / 60;
    secs = secs % 60;
    return string.Format("{0:D2}:{1:D2}:{2:D2}", hours, mins, secs);
}

How can I apply this string.Format when I'm using public Func<double, string> to calculate the times over 24 hours long.


Solution

  • You can use string.Format within you public Func<double, string>, just apply the values as parameters rather than a single string:

    Formatter = value => string.Format("{0:D2}:{1:D2}:{2:D2}", (int)(value - (value % 3600)) / 3600, (int)((value % 3600) - (value % 60)) / 60, (int)value % 60);
    

    Alternatively, as already stated, it's probably better to use the built in functions.