Skip to content

Commit

Permalink
Showing 2 changed files with 41 additions and 0 deletions.
26 changes: 26 additions & 0 deletions spec/std/time/time_spec.cr
Original file line number Diff line number Diff line change
@@ -646,6 +646,32 @@ describe Time do
(local - utc).should eq(0.seconds)
end

describe "days in month" do
it "returns days for valid month and year" do
Time.days_in_month(2016, 2).should eq(29)
Time.days_in_month(1990, 4).should eq(30)
end

it "raises exception for invalid month" do
expect_raises(ArgumentError, "Invalid month") do
Time.days_in_month(2016, 13)
end
end

it "raises exception for invalid year" do
expect_raises(ArgumentError, "Invalid year") do
Time.days_in_month(10000, 11)
end
end
end

it "days in year with year" do
Time.days_in_year(2005).should eq(365)
Time.days_in_year(2004).should eq(366)
Time.days_in_year(2000).should eq(366)
Time.days_in_year(1990).should eq(365)
end

typeof(Time.now.year)
typeof(1.minute.from_now.year)
typeof(1.minute.ago.year)
15 changes: 15 additions & 0 deletions src/time.cr
Original file line number Diff line number Diff line change
@@ -405,6 +405,11 @@ struct Time
def_hash total_seconds, nanosecond

# Returns how many days this *month* (`1..12`) of this *year* has (28, 29, 30 or 31).
#
# ```
# Time.days_in_month(2016, 2) # => 29
# Time.days_in_month(1990, 4) # => 30
# ```
def self.days_in_month(year : Int, month : Int) : Int32
unless 1 <= month <= 12
raise ArgumentError.new "Invalid month"
@@ -418,6 +423,16 @@ struct Time
days[month]
end

# Returns number of days in *year*.
#
# ```
# Time.days_in_year(1990) # => 365
# Time.days_in_year(2004) # => 366
# ```
def self.days_in_year(year : Int) : Int32
leap_year?(year) ? 366 : 365
end

# Returns whether this *year* is leap (February has one more day).
def self.leap_year?(year : Int) : Bool
unless 1 <= year <= 9999

0 comments on commit c8ee444

Please sign in to comment.