time: fix the string representation of a negative Duration (#21407)

This commit is contained in:
Henrik Holst 2024-05-03 10:51:42 -04:00 committed by GitHub
parent 7f7d7a1bb0
commit 4cb5949d14
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 19 additions and 6 deletions

View File

@ -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
@ -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' }
}
}

View File

@ -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'