ruby / rails中是否有方法可以添加/减去日期和时间以及时区,输出是天数,小时数,分钟数和秒数而不是DataTime格式?
t1 = "2012-05-05 00:00:02 -0400"
t2 = "2012-05-04 00:00:00 -0500"
time_diff = (Time.now() - Time.parse(t1)).to_s
#Or
time_diff = (Time.parse(t1) - Time.parse(t2)).to_s
我正在寻找1 Day, 01:59:58
结果应为#of Days HH:MM:SS
格式
答案 0 :(得分:8)
据我所知,Ruby或Rails没有内置任何功能。有distance_of_time_in_words
,但它比你想要的时间更短(例如“约7天”)。
尽管如此,编写一个方法来实现这一目标还算微不足道。给定秒数的差异,这将为您提供差异中的日,小时和秒:
def time_length seconds
days = (seconds / 1.day).floor
seconds -= days.days
hours = (seconds / 1.hour).floor
seconds -= hours.hours
minutes = (seconds / 1.minute).floor
seconds -= minutes.minutes
{ days: days, hours: hours, minutes: minutes, seconds: seconds }
end
time_length(Time.parse(t1) - Time.parse(t2))
#=> {:days=>0, :hours=>23, :minutes=>0, :seconds=>2.0}