Skip to content

Commit f08836b

Browse files
Stazerbyroot
authored andcommitted
Improve leap years counting performance in distance_of_time_in_words
1 parent b97917d commit f08836b

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

actionview/lib/action_view/helpers/date_helper.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,8 +136,15 @@ def distance_of_time_in_words(from_time, to_time = 0, options = {})
136136
from_year += 1 if from_time.month >= 3
137137
to_year = to_time.year
138138
to_year -= 1 if to_time.month < 3
139-
leap_years = (from_year > to_year) ? 0 : (from_year..to_year).count { |x| Date.leap?(x) }
139+
140+
leap_years = if from_year > to_year
141+
0
142+
else
143+
fyear = from_year - 1
144+
(to_year / 4 - to_year / 100 + to_year / 400) - (fyear / 4 - fyear / 100 + fyear / 400)
145+
end
140146
minute_offset_for_leap_year = leap_years * 1440
147+
141148
# Discount the leap year days when calculating year distance.
142149
# e.g. if there are 20 leap year days between 2 dates having the same day
143150
# and month then based on 365 days calculation

0 commit comments

Comments
 (0)