Home > OS >  Is there a way to remove trailing 0's from TimeSpan.Parse
Is there a way to remove trailing 0's from TimeSpan.Parse

Time:07-07

I have a Timespan that is HH:mm:ss.fffffff e.g. 12:13:08.1265838 and I use this code to format the Timespan to one decimal place:

Duration = TimeSpan.Parse(stopEventOut.StopEventDateTime.Subtract(stopEventIn.StopEventDateTime).ToString("hh':'mm':'ss'.'f")),

This format the code to one decimal place but leaves trailing 0's. (using the example above would format to 12:13:08.1000000)

Is there a way to remove these in the to string formatting, or any other way?

CodePudding user response:

Your code seems to be subtracting two datetimes to produce a TimeSpan, then calling .ToString() to format the result, and then redundantly parsing the result back to a TimeSpan again. So you format the string of the internal timespan (12:13:08.1265838) to "12:13:08.1" and then parse it back to a TimeSpan, where it becomes 12:13:08.1000000.

You should instead format after you're done with all the timespan calculations, and get rid of the redundant parsing:

Duration = stopEventOut.StopEventDateTime.Subtract(stopEventIn.StopEventDateTime),

// ... 

Console.WriteLine(Duration.ToString("hh':'mm':'ss'.'f")); // 12:13:08.1

As a small bonus, you could create some extension methods on TimeSpan to format your timespans accordingly like so:

public static class TimeSpanExtensions
{ 
    public static string WithTenthsOfASecond(this TimeSpan t)
    {
        return t.ToString("hh':'mm':'ss'.'f");
    } 

    public static string WithHundrethsOfASecond(this TimeSpan t)
    {
        return t.ToString("hh':'mm':'ss'.'ff");
    } 

    public static string WithMilliseconds(this TimeSpan t)
    {
        return t.ToString("hh':'mm':'ss'.'fff");
    } 
} 

Which then allows you to do:

Duration.WithTenthsOfASecond(); // "12:13:08.1"
Duration.WithHundrethsOfASecond(); // "12:13:08.12"
Duration.WithMilliseconds(); // "12:13:08.126"

CodePudding user response:

Instead of using f, use F. That won't display any trailing 0s.

https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-timespan-format-strings#F_Specifier

Also if you are viewing Duration in the debugger - there's a default format.

  • Related