Search code examples
c#timer

How to show timer in days after 24H using C# Timer


I've used System.Threading.Timer in my project like code below:

async Task Timer()
{
    timer = new System.Threading.Timer((_) =>
    {
        TimeSpan span = DateTime.Now.Subtract(ed);
        Time = (TimeSpan.FromTicks(span.Ticks).ToString()).Substring(0, 8);
        InvokeAsync(() =>
        {
            StateHasChanged();
        });
    }, null, 0, 1000);
}

how should I change it to show timer in days, after 24h? Thanks in advance


Solution

  • Timespans roll up to days level, they don't stop at counting hours. If you have a timespan that represents 23:59:59 and you add a second to it, you do not get 24:00:00 you get 1 day 00:00:00

    If you want it to count in hours forever you'll have to multiply the days back to hours yourself

    $"{t.Days*24+t.Hours}:{t.Minutes}:{t.Seconds}"
    

    You could also cut the decimal part off the total hours

    $"{(int)t.TotalHours}:{t.Minutes}:{t.Seconds}"
    
    $"{t.TotalHours:F0}:{t.Minutes}:{t.Seconds}"