2009-05-08 7 views
26

Comment vous formatez avec élégance un timespan dire par exemple « 1 heure 10 minutes » lorsque vous avez déclaré comme:Timespan mise en forme

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

?

Je suis bien sûr conscient que vous pourriez faire des mathématiques simples pour cela, mais j'espérais un peu qu'il ya quelque chose dans .NET pour gérer cela pour moi - pour des scénarios plus complexes

en double de How can I String.Format a TimeSpan object with a custom format in .NET?

Répondre

20

Il n'y a pas de fonctionnalité intégrée pour cela, vous aurez besoin d'utiliser une méthode personnalisée, quelque chose comme:

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") 
+1

Honte, malheureusement parfois le temps peut être <1 heure, de sorte que ne fera pas tout à fait. Devinez je vais devoir faire un peu de iffing :) Ty de toute façon – qui

+0

Lorsque son <1 heure, modifier la condition à partir de ce ts.Hours == 1? "": "s", ts.heures <= 1? "": "s", –

+0

@jalchr: Pluriel est correct pour les valeurs nulles, laissez-le comme '== 1'. par exemple. 0 heures, 0 minutes est correct. –

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; 
} 
+6

Votre code crie pour refactoriser! – TweeZz

1

J'aime la réponse sur laquelle John travaille. Voici ce que j'ai trouvé. Ne compte pas pendant des jours donc vous auriez besoin d'ajouter que si vous le souhaitez.

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"; 
} 
+0

Je viens de faire dans mon propre code, simple comme l'ajout d'un "ceci" avant le paramètre. –

+2

J'aimerais que le pluriel en russe soit aussi simple qu'en anglais =) –

+0

@ MaximV.Pavlov +1 commentaire hilarant> ;-) J'aimerais voir un pluralisateur russe qui pourrait écrire correctement "2345678" en mots dans le phrase "avec 2345678 filles". En fait, je n'ai pas encore rencontré un humain qui puisse le faire sans hésitation. – smirkingman

5

Copié ma propre réponse d'ici: 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; 
}