Timespan formatting [duplicate]
Asked Answered
A

5

26

How do you elegantly format a timespan to say example "1 hour 10 minutes" when you have declared it as :

TimeSpan t = new TimeSpan(0, 70, 0);

?

I am of course aware that you could do some simple maths for this, but I was kinda hoping that there is something in .NET to handle this for me - for more complicated scenarios

Duplicate of How can I String.Format a TimeSpan object with a custom format in .NET?

Ashraf answered 8/5, 2009 at 14:41 Comment(0)
M
21

There is no built-in functionality for this, you'll need to use a custom method, something like:

TimeSpan ts = new TimeSpan(0, 70, 0);
String.Format("{0} hour{1} {2} minute{3}", 
              ts.Hours, 
              ts.Hours == 1 ? "" : "s",
              ts.Minutes, 
              ts.Minutes == 1 ? "" : "s")
Makeup answered 8/5, 2009 at 14:51 Comment(3)
Shame, unfortunately sometimes the time can be <1 hour, so that wont quite do it. Guess i'll just have to do a bit of iffing :) Ty anywayAshraf
When its < 1 hour, modify the condition from this ts.Hours == 1 ? "" : "s", to this ts.Hours <= 1 ? "" : "s",Solferino
@jalchr: Plural is correct for zero values so leave it as == 1. e.g. 0 Hours, 0 Minutes is correct.Ingram
B
13
public static string Pluralize(int n, string unit)
{
    if (string.IsNullOrEmpty(unit)) return string.Empty;

    n = Math.Abs(n); // -1 should be singular, too

    return unit + (n == 1 ? string.Empty : "s");
}

public static string TimeSpanInWords(TimeSpan aTimeSpan)
{
    List<string> timeStrings = new List<string>();

    int[] timeParts = new[] { aTimeSpan.Days, aTimeSpan.Hours, aTimeSpan.Minutes, aTimeSpan.Seconds };
    string[] timeUnits = new[] { "day", "hour", "minute", "second" };

    for (int i = 0; i < timeParts.Length; i++)
    {
        if (timeParts[i] > 0)
        {
            timeStrings.Add(string.Format("{0} {1}", timeParts[i], Pluralize(timeParts[i], timeUnits[i])));
        }
    }

    return timeStrings.Count != 0 ? string.Join(", ", timeStrings.ToArray()) : "0 seconds";
}
Bemuse answered 8/5, 2009 at 16:13 Comment(3)
I just did in my own code, simple as adding a "this" before the parameter.Bemuse
I wish pluralizing in Russian would be as simple as it is in English =)Catharina
@MaximV.Pavlov +1 Hilarious comment >;-) I'd like to see a Russian pluraliser that could correctly write "2345678" in words in the sentence "with 2345678 girls". Actually, I've yet to meet a human that can do it without hesitation.Jejune
V
5

Copied my own answer from here: How do I convert a TimeSpan to a formatted string?

public static string ToReadableAgeString(this TimeSpan span)
{
    return string.Format("{0:0}", span.Days / 365.25);
}

public static string ToReadableString(this TimeSpan span)
{
    string formatted = string.Format("{0}{1}{2}{3}",
        span.Duration().Days > 0 ? string.Format("{0:0} days, ", span.Days) : string.Empty,
        span.Duration().Hours > 0 ? string.Format("{0:0} hours, ", span.Hours) : string.Empty,
        span.Duration().Minutes > 0 ? string.Format("{0:0} minutes, ", span.Minutes) : string.Empty,
        span.Duration().Seconds > 0 ? string.Format("{0:0} seconds", span.Seconds) : string.Empty);

    if (formatted.EndsWith(", ")) formatted = formatted.Substring(0, formatted.Length - 2);

    if (string.IsNullOrEmpty(formatted)) formatted = "0 seconds";

    return formatted;
}
Veats answered 9/5, 2012 at 8:41 Comment(0)
R
1
public static string GetDurationInWords( TimeSpan aTimeSpan )
{
    string timeTaken = string.Empty;

    if( aTimeSpan.Days > 0 )
        timeTaken += aTimeSpan.Days + " day" + ( aTimeSpan.Days > 1 ? "s" : "" );

    if( aTimeSpan.Hours > 0 )
    {
        if( !string.IsNullOrEmpty( timeTaken ) )
           timeTaken += " ";
        timeTaken += aTimeSpan.Hours + " hour" + ( aTimeSpan.Hours > 1 ? "s" : "" );
    }

    if( aTimeSpan.Minutes > 0 )
    {
       if( !string.IsNullOrEmpty( timeTaken ) )
           timeTaken += " ";
       timeTaken += aTimeSpan.Minutes + " minute" + ( aTimeSpan.Minutes > 1 ? "s" : "" );
    }

    if( aTimeSpan.Seconds > 0 )
    {
       if( !string.IsNullOrEmpty( timeTaken ) )
           timeTaken += " ";
       timeTaken += aTimeSpan.Seconds + " second" + ( aTimeSpan.Seconds > 1 ? "s" : "" );
    }

    if( string.IsNullOrEmpty( timeTaken ) )
        timeTaken = "0 seconds.";

     return timeTaken;
}
Republic answered 8/5, 2009 at 15:31 Comment(1)
Your code screams for refactoring!Dustan
F
1

I like the answer John is working on. Here's what I came up with.

Convert.ToDateTime(t.ToString()).ToString("h \"Hour(s)\" m \"Minute(s)\" s \"Second(s)\"");

Doesn't account for days so you'd need to add that if you want it.

Fining answered 8/5, 2009 at 15:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.