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
581 views
in Technique[技术] by (71.8m points)

.net - C# String Format for hours and minutes from decimal

Is there a simple string format that will take a decimal representing hours and fractions of hours and show it as hours and minutes?

For example : 5.5 formatted to display 5 hrs 30 minutes.

I am happy to write the code myself, however would prefer to use existing functionality if it is available

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
decimal t = 5.5M;
Console.WriteLine(TimeSpan.FromHours((double)t).ToString());

That'll give you "05:30:00" which is pretty close. You could then format that to your desired result:

var ts = TimeSpan.FromHours((double)t);
Console.WriteLine("{0} hrs {1} minutes", ts.Hours, ts.Minutes);

Note that there's a potential for loss of accuracy in the conversion from decimal to double, but I don't think it would be noticeable on the minute scale. Someone with a Skeet-like understanding of the type system might be able to chime in here.


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

...