Skip to content

Commit 2f4f4d2

Browse files
pacsofxn
authored andcommitted
Add days_in_year method
1 parent 9ccb341 commit 2f4f4d2

File tree

3 files changed

+33
-3
lines changed

3 files changed

+33
-3
lines changed

activesupport/CHANGELOG.md

+8-3
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,17 @@
33

44
To opt-in load the [listen](https://github.com/guard/listen) gem in `Gemfile`:
55

6-
group :development do
7-
gem 'listen', '~> 3.0.4'
8-
end
6+
group :development do
7+
gem 'listen', '~> 3.0.4'
8+
end
99

1010
*Puneet Agarwal* and *Xavier Noria*
1111

12+
* Added `Time#days_in_year` to return the number of days in the given year, or the
13+
current year if no argument is provided.
14+
15+
*Jon Pascoe*
16+
1217
* Updated `parameterize` to preserve the case of a string, optionally.
1318

1419
Example:

activesupport/lib/active_support/core_ext/time/calculations.rb

+6
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,12 @@ def days_in_month(month, year = current.year)
2626
end
2727
end
2828

29+
# Returns the number of days in the given year.
30+
# If no year is specified, it will use the current year.
31+
def days_in_year(year = current.year)
32+
days_in_month(2, year) + 337
33+
end
34+
2935
# Returns <tt>Time.zone.now</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns <tt>Time.now</tt>.
3036
def current
3137
::Time.zone ? ::Time.zone.now : ::Time.now

activesupport/test/core_ext/time_ext_test.rb

+19
Original file line numberDiff line numberDiff line change
@@ -617,6 +617,25 @@ def test_days_in_month_feb_in_leap_year_without_year_arg
617617
end
618618
end
619619

620+
def test_days_in_year_with_year
621+
assert_equal 365, Time.days_in_year(2005)
622+
assert_equal 366, Time.days_in_year(2004)
623+
assert_equal 366, Time.days_in_year(2000)
624+
assert_equal 365, Time.days_in_year(1900)
625+
end
626+
627+
def test_days_in_year_in_common_year_without_year_arg
628+
Time.stub(:now, Time.utc(2007)) do
629+
assert_equal 365, Time.days_in_year
630+
end
631+
end
632+
633+
def test_days_in_year_in_leap_year_without_year_arg
634+
Time.stub(:now, Time.utc(2008)) do
635+
assert_equal 366, Time.days_in_year
636+
end
637+
end
638+
620639
def test_last_month_on_31st
621640
assert_equal Time.local(2004, 2, 29), Time.local(2004, 3, 31).last_month
622641
end

0 commit comments

Comments
 (0)