C# 十进制字符串格式的小时和分钟
是否有一种简单的字符串格式,可以采用代表小时和小时分数的小数并将其显示为小时和分钟?
例如:5.5 格式化为显示 5 小时 30 分钟。
我很高兴自己编写代码,但更愿意使用现有的功能(如果可用)
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这会给你“05:30:00”,这非常接近。然后,您可以将其格式化为您想要的结果:
请注意,从十进制转换为双精度可能会损失准确性,但我认为这在分钟刻度上不会很明显。对类型系统有类似飞碟般理解的人也许能够在这里插话。
That'll give you "05:30:00" which is pretty close. You could then format that to your desired result:
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.
如果您的时间可能超过 24 小时,则必须考虑 TimeSpan 类具有 Days 属性,并且 Hours 属性将循环。这样可以防止超过 24 小时的任何错误:
If you have time that can be more than 24 hours, you have to consider that the TimeSpan class has a Days property, and the Hours property will cycle. Something like this will prevent any error from time with more than 24 hours:
我根据 Matt 的评论为此编写了一些小辅助方法。对于某人来说可能有用,可以让您自己编写它。
I wrote a few small helper methods for this based on Matt's comment. Might be useful for someone to save you writing it yourself.