127 votes

Comment convertir un TimeSpan en une chaîne formatée?

Double Possible:
Comment puis-je Chaîne.Le Format d'un objet TimeSpan avec un format personnalisé .NET?

Copie Exacte

Timespan mise en forme

Première question ici:

J'ai deux DateTime vars, beginTime et de la fin des temps. J'ai obtenu la différence d'eux, de la manière suivante:

TimeSpan dateDifference = endTime.Subtract(beginTime);

Comment puis-je retourner une chaîne de cette hh h, mm les minutes, ss secondes format à l'aide de C#.

Si la différence était 00:06:32.4458750

Il devrait revenir ce 00, 06 minutes, 32 secondes

Merci pour l'aide

198voto

Peter Points 5678

Je viens de construire quelques méthodes d'extension TimeSpan. Je pensais pouvoir partager:

 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} day{1}, ", span.Days, span.Days == 1 ? String.Empty : "s") : string.Empty,
        span.Duration().Hours > 0 ? string.Format("{0:0} hour{1}, ", span.Hours, span.Hours == 1 ? String.Empty : "s") : string.Empty,
        span.Duration().Minutes > 0 ? string.Format("{0:0} minute{1}, ", span.Minutes, span.Minutes == 1 ? String.Empty : "s") : string.Empty,
        span.Duration().Seconds > 0 ? string.Format("{0:0} second{1}", span.Seconds, span.Seconds == 1 ? String.Empty : "s") : string.Empty);

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

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

    return formatted;
}
 

144voto

vdboor Points 6259

En le convertissant en date / heure, vous pouvez obtenir des formats localisés:

 new DateTime(timeSpan.Ticks).ToString("HH:mm");
 

126voto

Ruberoid Points 218

C'est la solution la plus courte.

 timeSpan.ToString(@"hh\:mm");
 

47voto

Andy Points 15910

Est-ce que TimeSpan.ToString () ferait l'affaire pour vous? Sinon, il semble que l'exemple de code de cette page explique comment formater de manière personnalisée un objet TimeSpan .

36voto

GBegen Points 3621

Utilisez String.Format () avec plusieurs paramètres.

 using System;

namespace TimeSpanFormat
{
    class Program
    {
    	static void Main(string[] args)
    	{
    		TimeSpan dateDifference = new TimeSpan(0, 0, 6, 32, 445);
    		string formattedTimeSpan = string.Format("{0:D2} hrs, {1:D2} mins, {2:D2} secs", dateDifference.Hours, dateDifference.Minutes, dateDifference.Seconds);
    		Console.WriteLine(formattedTimeSpan);
    	}
    }
}
 

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X