在3行代码中,如何将字符串格式的毫秒转换为Ruby格式的HH:MM:SS? @scores\u raw.每个人都做| #下面是以毫秒为单位发送时间的代码 hh=((原始分数到分数)/100)/3600 毫米=(高高高高高高远至_i)*60 ss=(毫米至毫米)*60 碎屑=[hh,mm,ss] sum=crumps.first.to_i*3600+crumps[1]。to_i*60+crumps.last.to_i @分数总和:hms=>hh.round.to_s+”:“+mm.round.to_s+”:“+ss.round.to_s}” @分数散列和:hms=>hh.round.to_s+”:“+mm.round.to_s+”:“+ss.round.to_s} #毫秒案例结束 结束
这是我目前的代码,但我讨厌它。看起来很乱。它不仅看起来很棒。也许有人的ruby专家可以通过链接收集、减少等并使其看起来很好来告诉你如何做到这一点?你可以将其包装在一个助手方法中:在3行代码中,如何将字符串格式的毫秒转换为Ruby格式的HH:MM:SS? @scores\u raw.每个人都做| #下面是以毫秒为单位发送时间的代码 hh=((原始分数到分数)/100)/3600 毫米=(高高高高高高远至_i)*60 ss=(毫米至毫米)*60 碎屑=[hh,mm,ss] sum=crumps.first.to_i*3600+crumps[1]。to_i*60+crumps.last.to_i @分数总和:hms=>hh.round.to_s+”:“+mm.round.to_s+”:“+ss.round.to_s}” @分数散列和:hms=>hh.round.to_s+”:“+mm.round.to_s+”:“+ss.round.to_s} #毫秒案例结束 结束,ruby,Ruby,这是我目前的代码,但我讨厌它。看起来很乱。它不仅看起来很棒。也许有人的ruby专家可以通过链接收集、减少等并使其看起来很好来告诉你如何做到这一点?你可以将其包装在一个助手方法中: @scores_raw.each do |score_raw| # below is code if time was being sent in milliseconds hh = ((score_raw.score.to_i)/100)/3600 mm = (hh-hh.to_i)*60 ss =
@scores_raw.each do |score_raw|
# below is code if time was being sent in milliseconds
hh = ((score_raw.score.to_i)/100)/3600
mm = (hh-hh.to_i)*60
ss = (mm-mm.to_i)*60
crumbs = [hh,mm,ss]
sum = crumbs.first.to_i*3600+crumbs[1].to_i*60+crumbs.last.to_i
@scores << {:secs => sum, :hms => hh.round.to_s+":"+mm.round.to_s+":"+ss.round.to_s}
@scores_hash << {:secs => sum, :hms => hh.round.to_s+":"+mm.round.to_s+":"+ss.round.to_s}
# milliseconds case end
end
@Mike Woodhouse给出了很好的解决方案: 使用
divmod
:
def format_milisecs(m)
secs, milisecs = m.divmod(1000) # divmod returns [quotient, modulus]
mins, secs = secs.divmod(60)
hours, mins = mins.divmod(60)
[secs,mins,hours].map { |e| e.to_s.rjust(2,'0') }.join ':'
end
format_milisecs 10_600_00
=> "03:13:20"
答案是ruby提供的时间类提供了从秒获取时间的函数。用这个会治好的
t = 270921000
ss, ms = t.divmod(1000) #=> [270921, 0]
mm, ss = ss.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
或者获取utc时间
miliseconds = 32290928
seconds = miliseconds/1000
Time.at(seconds).strftime("%H:%M:%S")
谢谢,这是LOC的最短数量。@qwexar在
at
的问题是您需要从1970
开始计算毫秒数<代码>时间。时间(0)#=>1970年1月1日星期四05:30:00+0530。而at
函数不会给出mili秒
等效HH:MM:SS
。它根据时间来划分结果。在(0)@Taimoor Changaiz它不正确,它给出了时间相对于时间。在(0)@checkit,那么使用at方法获取当前时间的技巧是什么,我想我们可以用相对操作给定的毫秒?你把数组中的顺序弄混了吗?我本以为[小时、分钟、秒]
。
#Get UTC Time
Time.at(seconds).utc.strftime("%H:%M:%S")