两个日期之间的差异

时间:2021-08-15 21:27:21

I have 2 dates and difference between them can be over a month. I want to find a difference between them in day. However, b.days - a.days turns a blind eye to to the months and, possibly, years too.

我有两个日期,他们之间的差异可能超过一个月。我想在白天找到它们之间的区别。然而,b.days - a.days对这几个月甚至几年也视而不见。

require 'date'

a = Date.parse("20141030")
b = Date.parse("20141230")

b.day - a.day #=> 0

What's the easier way to find such a difference?

找到这种差异的更简单方法是什么?

1 个解决方案

#1


3  

Just subtract the one from the other:

只需从另一个中减去一个:

(b - a)
# => (61/1)
(b - a).to_i
# => 61

The reason you got 0 is b.day and a.day returns day of the month: 30. (30 - 30 = 0)

你得到0的原因是b.day和a.day返回月份的日期:30。(30 - 30 = 0)

b.day
# => 30
a.day
# => 30

#1


3  

Just subtract the one from the other:

只需从另一个中减去一个:

(b - a)
# => (61/1)
(b - a).to_i
# => 61

The reason you got 0 is b.day and a.day returns day of the month: 30. (30 - 30 = 0)

你得到0的原因是b.day和a.day返回月份的日期:30。(30 - 30 = 0)

b.day
# => 30
a.day
# => 30