如何将 270921sec 转换为天 + 小时 + 分钟 + 秒?(红宝石) [英] how to convert 270921sec into days + hours + minutes + sec ? (ruby)

查看:35
本文介绍了如何将 270921sec 转换为天 + 小时 + 分钟 + 秒?(红宝石)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几秒钟的时间.比方说 270921.我怎样才能显示那个数字,说它是 xx 天、yy 小时、zz 分钟、ww 秒?

I have a number of seconds. Let's say 270921. How can I display that number saying it is xx days, yy hours, zz minutes, ww seconds?

推荐答案

使用 divmod 可以非常简洁地完成:

It can be done pretty concisely using divmod:

t = 270921
mm, ss = t.divmod(60)            #=> [4515, 21]
hh, mm = mm.divmod(60)           #=> [75, 15]
dd, hh = hh.divmod(24)           #=> [3, 3]
puts "%d days, %d hours, %d minutes and %d seconds" % [dd, hh, mm, ss]
#=> 3 days, 3 hours, 15 minutes and 21 seconds

您可能可以通过使用 collectinject 发挥创意来进一步干燥它,但是当核心逻辑是三行时,它可能会过大.

You could probably DRY it further by getting creative with collect, or maybe inject, but when the core logic is three lines it may be overkill.

这篇关于如何将 270921sec 转换为天 + 小时 + 分钟 + 秒?(红宝石)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆