Need only HH:MM:SS in time span string

*爱你&永不变心* 提交于 2020-01-06 06:45:14

问题


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#?


回答1:


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);



回答2:


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 :)




回答3:


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



回答4:


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;


来源:https://stackoverflow.com/questions/31309526/need-only-hhmmss-in-time-span-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!