Remove leading zeros from time to show elapsed time
Asked Answered
R

7

10

I need to display simplest version of elapsed time span. Is there any ready thing to do that?

Samples:

HH:mm:ss
10:43:27 > 10h43m27s
00:04:12 > 4m12s
00:00:07 > 7s

I think I need a format provider for elapsed time.

Reexamine answered 22/3, 2011 at 21:47 Comment(1)
For reference: Existing Timespan formatters msdn.microsoft.com/en-us/library/ee372287.aspxPapiamento
W
12

Simple extension method should be enough:

static class Extensions
{ 
    public static string ToShortForm(this TimeSpan t)
    {
        string shortForm = "";
        if (t.Hours > 0)
        {
            shortForm += string.Format("{0}h", t.Hours.ToString());
        }
        if (t.Minutes > 0)
        {
            shortForm += string.Format("{0}m", t.Minutes.ToString());
        }
        if (t.Seconds > 0)
        {
            shortForm += string.Format("{0}s", t.Seconds.ToString());
        }
        return shortForm;
    } 
} 

Test it with:

TimeSpan tsTest = new TimeSpan(10, 43, 27);
string output = tsTest.ToShortForm();
tsTest = new TimeSpan(0, 4, 12);
output = tsTest.ToShortForm();
tsTest = new TimeSpan(0, 0, 7);
output = tsTest.ToShortForm();
Wideman answered 22/3, 2011 at 22:12 Comment(3)
P.S: It's not .NET v2.0 compatible.Reexamine
In .NET v2.0, the C# style answer would be: String.Format(new TimeSpanFormatProvider(), "Elapsed time is {0:ts}", timeSpan)Reexamine
This doesn't work for spans greater than 24 hours or less than one second. For example a span of 26 hours (1 day, 2 hours) will return only as "2h". A span of exactly 24 hours will return an empty string (no hours, minutes, or seconds). Add a check for days, or use t.TotalHours to show total elapsed hours. For spans of less than one second, check for an empty string at the end:` If String.IsNullOrEmpty(shortForm) Then shortForm = String.Format("{0}s", t.ToString("s\.ff")) End IfHeelandtoe
I
18

Here's a one-liner (almost), assuming you have the TimeSpan objectL

(new TimeSpan(0, 0, 30, 21, 3))
  .ToString(@"d\d\ hh\hmm\mss\s")
  .TrimStart(' ','d','h','m','s','0');

The sample code outputs

30m21s

The first line just makes a TimeSpan object for the sake of an example, .ToString formats it in the format you're asking for and then .TrimStart removes the leading characters you don't need.

Isogamete answered 7/4, 2014 at 20:41 Comment(2)
great solution! how could we incorporate milliseconds to this one liner?Samuel
@Samuel f is for fractions of a second, you can add 3 for ms or more for mks:(new TimeSpan(0, 0, 30, 21, 3, 54)) .ToString(@"d\d\ hh\hmm\mss\.ffffff\s") .TrimStart(' ', 'd', 'h', 'm', 's', '0')Isogamete
W
12

Simple extension method should be enough:

static class Extensions
{ 
    public static string ToShortForm(this TimeSpan t)
    {
        string shortForm = "";
        if (t.Hours > 0)
        {
            shortForm += string.Format("{0}h", t.Hours.ToString());
        }
        if (t.Minutes > 0)
        {
            shortForm += string.Format("{0}m", t.Minutes.ToString());
        }
        if (t.Seconds > 0)
        {
            shortForm += string.Format("{0}s", t.Seconds.ToString());
        }
        return shortForm;
    } 
} 

Test it with:

TimeSpan tsTest = new TimeSpan(10, 43, 27);
string output = tsTest.ToShortForm();
tsTest = new TimeSpan(0, 4, 12);
output = tsTest.ToShortForm();
tsTest = new TimeSpan(0, 0, 7);
output = tsTest.ToShortForm();
Wideman answered 22/3, 2011 at 22:12 Comment(3)
P.S: It's not .NET v2.0 compatible.Reexamine
In .NET v2.0, the C# style answer would be: String.Format(new TimeSpanFormatProvider(), "Elapsed time is {0:ts}", timeSpan)Reexamine
This doesn't work for spans greater than 24 hours or less than one second. For example a span of 26 hours (1 day, 2 hours) will return only as "2h". A span of exactly 24 hours will return an empty string (no hours, minutes, or seconds). Add a check for days, or use t.TotalHours to show total elapsed hours. For spans of less than one second, check for an empty string at the end:` If String.IsNullOrEmpty(shortForm) Then shortForm = String.Format("{0}s", t.ToString("s\.ff")) End IfHeelandtoe
M
3

You can use string.Format to achieve this, along with some conditional statements:

public static string GetSimplestTimeSpan(TimeSpan timeSpan)
{
    var result = string.Empty;
    if (timeSpan.Days > 0)
    {
        result += string.Format(
            @"{0:ddd\d}", timeSpan).TrimStart('0');
    }
    if (timeSpan.Hours > 0)
    {
        result += string.Format(
            @"{0:hh\h}", timeSpan).TrimStart('0');
    }
    if (timeSpan.Minutes > 0)
    {
        result += string.Format(
            @"{0:mm\m}", timeSpan).TrimStart('0');
    }
    if (timeSpan.Seconds > 0)
    {
        result += string.Format(
            @"{0:ss\s}", timeSpan).TrimStart('0');
    }
    return result;
}

Though, seeing the answer by BrokenGlass I'm tempted to say using Format here at all is overkill. However, it does allow you to tweak the output of each element of the elapsed time span if required.

Mungovan answered 22/3, 2011 at 21:52 Comment(4)
It doesn't trim zero day, hour, minute, etc... This is the result for 2s388f :00:02.3881813Reexamine
Of course it does - TimeSpan(0, 0, 0, 2, 388); results in 2s. Though I could update it to account for milliseconds as right now it doesn't care about them due to the request being to display the simplest form.Mungovan
Strange; (TimeSpan){00:00:02.4100804} returns (String)":00:02.4100804" here -in .Net v2.0-Reexamine
I stand corrected, tested myself and this is very definitely broken on .NET 2.Mungovan
K
3

I don't think this can be done in a straightforward way doing a custom format serializer - I'd just roll my own:

TimeSpan delta = TimeSpan.Parse("09:03:07");
string displayTime = string.Empty;
if (delta.Hours > 0)
    displayTime += delta.Hours.ToString() + "h";

if (delta.Minutes > 0)
    displayTime += delta.Minutes.ToString() + "m";

if (delta.Seconds > 0)
    displayTime += delta.Seconds.ToString() + "s";

Note that this would only work for positive time spans.

Kidding answered 22/3, 2011 at 22:3 Comment(1)
I call this way as Indian style :)Reexamine
C
2

Here's my take:

    Dim TimeTaken As String = TimeSpan.ToString("g") ' Supply TimeSpan
    If TimeTaken.Contains("0:00") Then
        TimeTaken = TimeTaken.Remove(0, 3)
    ElseIf TimeTaken.Contains("0:0") Then
        TimeTaken = TimeTaken.Remove(0, 2)
    End If
Crescentia answered 24/4, 2017 at 0:46 Comment(0)
I
0
public static string ToFriendlyString(this TimeSpan timeSpan)
{
    string result = string.Empty;

    if (Math.Floor(timeSpan.TotalDays) > 0.0d)
        result += string.Format(@"{0:ddd}d ", timeSpan).TrimFirst('0');
    if (Math.Floor(timeSpan.TotalHours) > 0.0d)
        result += string.Format(@"{0:hh}h ", timeSpan).TrimFirst('0');
    if (Math.Floor(timeSpan.TotalMinutes) > 0.0d)
        result += string.Format(@"{0:mm}m ", timeSpan).TrimFirst('0');
    if (Math.Floor(timeSpan.TotalSeconds) > 0.0d)
        result += string.Format(@"{0:ss}s ", timeSpan).TrimFirst('0');
    else
        result += "0s";

    return result;
}

public static string TrimFirst(this string value, char c)
{
    if (value[0] == c)
        return value[1..];

    return value;
}
Irritable answered 16/4, 2022 at 14:48 Comment(0)
I
0

If any one need auto day string without elapsed zero.

You can try toString("c")

new TimeSpan(41,48, 2, 3).ToString("c")

will get result:

43.00:02:03

You can get more info in MSDN. TimeSpan.ToString Method

Immemorial answered 3/1, 2023 at 8:8 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.