I want to format TimeSpans in C# in this way:
xxx day(s) yyy hours(s) zzz minute(s)
Conditions:
Extra seconds should be truncated
day(s) is the largest unit I want. I want 34 days to appear as 34 days rather than 1 month 4 days etc.
If timespan is less than one day, I dont want the day part to show up. Likewise if span is less than 1 hour, I want only the mins part to show up.
Is there any way I can do this using built-in format strings or there is no way other than writing my own function?
Edit: Currently using my own function for this. It takes TimeSpan in minutes as input (TimeSpan.TotalMinutes)
:
private static string GetTimeStringFromMinutes(double p)
{
var minutes = (int) p;
int hours = minutes / 60;
minutes = minutes % 60;
int days = hours/24;
hours = hours%24;
string dayPart = days + " day(s) ";
string hoursPart = hours + " hour(s) ";
string minutesPart = minutes + " minute(s)";
if (days != 0)
return (dayPart + hoursPart + minutesPart);
if (hours != 0)
return (hoursPart + minutesPart);
return (minutesPart);
}
TimeSpan has no formatting options at all before .NET 4.0, you'd have to convert it to DateTime through the Ticks property. Nothing remotely close in DateTime.String(format) formatting options though, you'll have to write it yourself.
In .NET 4.0, TimeSpan acquired a ToString(format) override. Custom formatting strings are described here. Your 3rd requirement is going to need code.
In .NET 3.5 and earlier you need to write your own function.
In .NET 4 support was added for formatting TimeSpan
, see TimeSpan.ToString(string)
for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With