Double Possible:
Comment puis-je Chaîne.Le Format d'un objet TimeSpan avec un format personnalisé .NET?Copie Exacte
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
Cette question a déjà des réponses:
Réponses
Trop de publicités?
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;
}
vdboor
Points
6259
Ruberoid
Points
218
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
.
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);
}
}
}