Skip to content

Commit 9937b8b

Browse files
authored
Add weeks parameter to Time::Span.new (#16208)
1 parent a86e9b3 commit 9937b8b

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

spec/std/time/span_spec.cr

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ describe Time::Span do
3030
t1 = Time::Span.new days: -1, hours: 2, minutes: -3, seconds: 4, nanoseconds: -5_000_000
3131
t1.to_s.should eq("-22:02:56.005000000")
3232

33+
t1 = Time::Span.new weeks: 1, days: 2, hours: 3, minutes: 4, seconds: 5, nanoseconds: 6_000_000
34+
t1.to_s.should eq("9.03:04:05.006000000")
35+
3336
t1 = Time::Span.new hours: 25
3437
t1.to_s.should eq("1.01:00:00")
3538
end

src/time/span.cr

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ struct Time::Span
9393
new(seconds: 0, nanoseconds: nanoseconds)
9494
end
9595

96-
# Creates a new `Time::Span` from the *days*, *hours*, *minutes*, *seconds* and *nanoseconds* given
96+
# Creates a new `Time::Span` from the *weeks, *days*, *hours*, *minutes*, *seconds* and *nanoseconds* given
9797
#
9898
# Any time unit can be omitted.
9999
#
@@ -102,19 +102,20 @@ struct Time::Span
102102
# Time::Span.new(days: 1, hours: 2, minutes: 3) # => 1.02:03:00
103103
# Time::Span.new(days: 1, hours: 2, minutes: 3, seconds: 4, nanoseconds: 5) # => 1.02:03:04.000000005
104104
# ```
105-
def self.new(*, days : Int = 0, hours : Int = 0, minutes : Int = 0, seconds : Int = 0, nanoseconds : Int = 0)
105+
def self.new(*, weeks : Int = 0, days : Int = 0, hours : Int = 0, minutes : Int = 0, seconds : Int = 0, nanoseconds : Int = 0)
106106
new(
107-
seconds: compute_seconds(days, hours, minutes, seconds),
107+
seconds: compute_seconds(weeks, days, hours, minutes, seconds),
108108
nanoseconds: nanoseconds,
109109
)
110110
end
111111

112-
private def self.compute_seconds(days, hours, minutes, seconds)
112+
private def self.compute_seconds(weeks, days, hours, minutes, seconds)
113+
weeks_to_seconds = SECONDS_PER_WEEK.to_i64 * weeks
113114
days_to_seconds = SECONDS_PER_DAY.to_i64 * days
114115
hours_to_seconds = SECONDS_PER_HOUR.to_i64 * hours
115116
minutes_to_seconds = SECONDS_PER_MINUTE.to_i64 * minutes
116117

117-
days_to_seconds + hours_to_seconds + minutes_to_seconds + seconds
118+
weeks_to_seconds + days_to_seconds + hours_to_seconds + minutes_to_seconds + seconds
118119
rescue OverflowError
119120
raise ArgumentError.new "Time::Span too big or too small"
120121
end

0 commit comments

Comments
 (0)