Skip to content

Commit

Permalink
time: fix the string representation of a negative Duration (#21407)
Browse files Browse the repository at this point in the history
  • Loading branch information
hholst80 committed May 3, 2024
1 parent 7f7d7a1 commit 4cb5949
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
17 changes: 11 additions & 6 deletions vlib/time/duration.v
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,12 @@ pub fn (d Duration) str() string {
if d == time.infinite {
return 'inf'
}
mut sign := ''
mut t := i64(d)
if t < 0 {
sign = '-'
t = -t
}
hr := t / time.hour
t -= hr * time.hour
min := t / time.minute
Expand All @@ -77,12 +82,12 @@ pub fn (d Duration) str() string {
ns := t

return match true {
hr > 0 { '${hr}:${min:02}:${sec:02}' }
min > 0 { '${min}:${sec:02}.${ms:03}' }
sec > 0 { '${sec}.${ms:03}s' }
ms > 0 { '${ms}.${us:03}ms' }
us > 0 { '${us}.${ns:03}us' }
else { '${ns}ns' }
hr > 0 { '${sign}${hr}:${min:02}:${sec:02}' }
min > 0 { '${sign}${min}:${sec:02}.${ms:03}' }
sec > 0 { '${sign}${sec}.${ms:03}s' }
ms > 0 { '${sign}${ms}.${us:03}ms' }
us > 0 { '${sign}${us}.${ns:03}us' }
else { '${sign}${ns}ns' }
}
}

Expand Down
8 changes: 8 additions & 0 deletions vlib/time/duration_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@ fn test_duration_str() {
assert time.Duration(168 * time.hour + 5 * time.minute + 7 * time.second).str() == '168:05:07'
}

fn test_negative_duration() {
now := time.parse('2000-01-01 10:00:00')!
later := time.parse('2000-01-01 11:00:00')!
duration := now - later
assert time.Duration(-1 * time.hour) == duration
assert duration.str() == '-1:00:00'
}

fn test_duration_debug() {
assert time.Duration(1 * time.nanosecond).debug() == 'Duration: 1ns'
assert time.Duration(169 * time.hour + 5 * time.minute + 7 * time.second).debug() == 'Duration: 7days, 1h, 5m, 7s'
Expand Down

0 comments on commit 4cb5949

Please sign in to comment.