I have a time span string as
1.21:00:00
it means 45 hours and i need it as
45:00:00
is it possible to do that in c#?
I have a time span string as
1.21:00:00
it means 45 hours and i need it as
45:00:00
is it possible to do that in c#?
Just adding my answer because the string formatting can be done easier than current suggestions.
var ts = TimeSpan.Parse("1.21:00:00");
string.Format("{0}:{1:mm}:{1:ss}", ts.TotalHours, ts); // 45:00:00
Unlike Jon's answer it doesn't require escaping. And unlike Soner's answer, it doesn't require passing the parameter twice.
Edit
For fractional TotalHours you probably want to floor the value like so:
var ts = TimeSpan.Parse("1.21:55:00");
string.Format("{0}:{1:mm}:{1:ss}", Math.Floor(ts.TotalHours), ts);
Unfortunately I don't think the TimeSpan
custom formatting makes this feasible :(
You could either perform the string formatting yourself...
string text = (int) span.TotalHours + span.ToString(@"\:mm\:ss");
Or
string text = string.Format(@"{0}:{1:mm\:ss}", (int) span.TotalHours, span);
... or you could use my Noda Time library, which does allow for this:
// Or convert from a TimeSpan to a Duration
var duration = Duration.FromHours(50);
var durationPattern = DurationPattern.CreateWithInvariantCulture("HH:mm:ss");
Console.WriteLine(durationPattern.Format(duration)); // 50:00:00
Obviously I'd recommend moving your whole code base over to Noda Time to make all your date/time code clearer, but I'm biased :)
If this is string and your CurrentCulture
has :
as a TimeSeparator
, you can use like;
var ts = TimeSpan.Parse("1.21:00:00");
string.Format("{0}:{1:mm}:{2:ss}", ts.TotalHours, ts, ts); // 45:00:00
or you can combine minute and second parts as Jon did like;
string.Format(@"{0}:{1:mm\:ss}", ts.TotalHours, ts) // 45:00:00
You can use Span.TotalHours
property to get total hours from a time span.
TimeSpan span;
string timeSpan = "1.21:00:00";
TimeSpan.TryParse(timeSpan, out span);
double hours = span.TotalHours;