0

我有一个 ruby​​ 应用程序,我需要获取 Days-Hours-Minutes 格式的日期时间差。为此我使用以下功能

def duration  (from_time, to_time)
   from_time = from_time.to_time if from_time.respond_to?(:to_time)
   to_time = to_time.to_time if to_time.respond_to?(:to_time)
   distance_in_seconds = ((to_time - from_time).abs).round

   secs  = distance_in_seconds.to_int
   mins  = secs / 60
   hours = mins / 60
   days  = hours / 24

   if days > 0
     "#{days}d #{hours % 24}h"
   elsif hours > 0
     "#{hours}h #{mins % 60}m"
   elsif mins > 0
     "#{mins}m"
 end
end

上面从另一个函数中这样调用

duration(aw_updated, Time.now)

但有时它给了我错误的结果,

当我显示上述值时

aw_updated is 2012-09-19 04:23:34 UTC
Time.now is   2012-09-19 16:33:09 +0530
Time.now.utc is 2012-09-19 11:03:09 UTC 

Diff is 6h 26m

但是我的系统时间是2012-09-19 16:33:09

不确定我在哪里做错了,一些 UTC 问题?

请指教

4

2 回答 2

0

对于正确答案utc,在这种情况下,您的两个时间都应该有相同的时区

所以它正在转换2012-09-19 16:33:09 +0530utc哪个给出2012-09-19 11:03:09 UTC,因此差异是 Diff 是 6h 26m

于 2012-09-19T11:08:13.017 回答
0

将其作为评论输入,但还不能。

我没有详细查看您的功能,但您必须从头开始构建它吗?为什么不在内置的DateTime类中使用 Ruby。您可以将字符串解析为 DateTime 对象,进行计算并使用strftime方法以您想要的格式输出时间

于 2012-09-19T11:09:03.967 回答