2012-09-19 26 views
0

我有一个红宝石应用程序,我需要以天 - 小时 - 分钟格式获取日期 - 时间差。对于这个即时通讯使用下面的函数ROR中的日期时间差

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 

And

Diff is 6h 26m 

但是我的系统时间为2012-09-19 16点33分09秒

不知道在哪里在做错误的,有些UTC问题?

请指教

+0

对我来说看起来很好。您的系统时间显示UTC + 5.30 – Sebi

+0

差异不应超过12小时? –

+0

04:23:34和11:03:09之间的区别是6h:39m:35s。尝试再次运行代码并发布输出。 – Sebi

回答

0

为正确答案你的两个时间应该有相同的时区utc在这种情况下

所以它转换2012-09-19 16:33:09 +0530utc这给2012-09-19 11:03:09 UTC,因此不同的是DIFF为6h26米

+0

我明白了,谢谢........ –

0

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

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