Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...