time: Time.add (#7262)

pull/7281/head^2
Takahiro Yaota 2020-12-12 12:22:30 +09:00 committed by GitHub
parent 11808f9fa3
commit eb48208599
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 3 deletions

View File

@ -171,15 +171,22 @@ pub fn (t Time) unix_time_milli() u64 {
return t.unix * 1000 + u64(t.microsecond / 1000)
}
// add returns a new time that duration is added
pub fn (t Time) add(d Duration) Time {
microseconds := i64(t.unix) * 1000 * 1000 + t.microsecond + d.microseconds()
unix := microseconds / (1000 * 1000)
micro := microseconds % (1000 * 1000)
return unix2(int(unix), int(micro))
}
// add_seconds returns a new time struct with an added number of seconds.
pub fn (t Time) add_seconds(seconds int) Time {
// TODO Add(d time.Duration)
return unix(int(t.unix + u64(seconds)))
return t.add(seconds * second)
}
// add_days returns a new time struct with an added number of days.
pub fn (t Time) add_days(days int) Time {
return unix(int(t.unix + u64(i64(days) * 3600 * 24)))
return t.add(days * 24 * hour)
}
// since returns a number of seconds elapsed since a given time.

View File

@ -153,6 +153,21 @@ fn test_weekday_str() {
}
}
fn test_add() {
d_seconds := 3
d_microseconds := 13
duration := time.Duration(d_seconds * time.second + d_microseconds * time.microsecond)
t1 := time_to_test
t2 := time_to_test.add(duration)
assert t2.second == t1.second + d_seconds
assert t2.microsecond == t1.microsecond + d_microseconds
assert t2.unix == t1.unix + u64(d_seconds)
t3 := time_to_test.add(-duration)
assert t3.second == t1.second - d_seconds
assert t3.microsecond == t1.microsecond - d_microseconds
assert t3.unix == t1.unix - u64(d_seconds)
}
fn test_add_days() {
num_of_days := 3
t := time_to_test.add_days(num_of_days)