开发者

Operations on DateTime in rails

开发者 https://www.devze.com 2023-03-30 16:32 出处:网络
Is it possible to subtract one DateTime from another and get the result in Time. Example if we subtract 2011-08-27 01:00:00 UTC from 2011-08-29 08:13:00 UTC, the result should be 55:13:00 (hope I didn

Is it possible to subtract one DateTime from another and get the result in Time. Example if we subtract 2011-08-27 01:00:00 UTC from 2011-08-29 08:13:00 UTC, the result should be 55:13:00 (hope I didn't make a mistake while ca开发者_运维技巧lulating :p) Thanks.


Time is generally expressed in seconds when doing math like this, even fractional seconds if you want. A Time represents a specific point in time, which while internally represented as seconds since the January 1, 1970 epoch, is not intended to be a scalar unit like that.

If you have two DateTime objects, you can determine the difference between them like this:

diff = DateTime.parse('2011-08-29 08:13:00 UTC').to_time - DateTime.parse('2011-08-27 01:00:00 UTC').to_time
# => 198780.0

Once you have the number of seconds, the rest is simply a formatting problem:

'%d:%02d:%02d' % [ diff / 3600, (diff / 60) % 60, diff % 60 ]
# => "55:13:00"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号