Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

c# - Format TimeSpan greater than 24 hour

Say I convert some seconds into the TimeSpan object like this:

Dim sec = 1254234568
Dim t As TimeSpan = TimeSpan.FromSeconds(sec)

How do I format the TimeSpan object into a format like the following:

>105hr 56mn 47sec

Is there a built-in function or do I need to write a custom function?

question from:https://stackoverflow.com/questions/3505230/format-timespan-greater-than-24-hour

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, the simplest thing to do is to format this yourself, e.g.

return string.Format("{0}hr {1}mn {2}sec",
                     (int) span.TotalHours,
                     span.Minutes,
                     span.Seconds);

In VB:

Public Shared Function FormatTimeSpan(span As TimeSpan) As String
    Return String.Format("{0}hr {1}mn {2}sec", _
                         CInt(Math.Truncate(span.TotalHours)), _
                         span.Minutes, _
                         span.Seconds)
End Function

I don't know whether any of the TimeSpan formatting in .NET 4 would make this simpler.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...