dugwill
(Dugwill)
April 3, 2016, 2:43pm
#1
New to GO. I am working through the Donovan/Kernighan book.
I am trying to compare two time.Time variables in an if statement.
if item.CreatedAt < yearAgo {
…
}
Both var are of type time.Time. “item.CreatedAt” is from a struct and yearAgo is calculated:
t0 := time.Now()
var yearAgo time.Time = t0.Add(-timeCalc.OneYear)
when I build this is get an error:
github.com \dugwill\gopl.io \ch4\issues\main.go:41: invalid operation: item.CreatedAt < yearAgo (operator < not defined on struct)
I would expect this, I think, if I would comparing two structs. I don’t understand why I get it when comparing to vars of the same type.
Code can be found at
github.com/dugwill/gopl.io/blob/Chapter4/ch4/issues/main.go
Regards
geosoft1
(George Calianu)
April 3, 2016, 3:06pm
#2
you can compare as Unix time
package main
import(
"fmt"
"time"
)
func main(){
t0 := time.Now().Unix()
time.Sleep(time.Second*3)
t1 := time.Now().Unix()
fmt.Println(t1 - t0)
}
Running…
3
Success: process exited with code 0.
calmh
(Jakob Borg)
April 3, 2016, 3:44pm
#3
Or, perhaps better:
if t0.Before(t1) {
// true when t0 < t1
}
diff := t0.Sub(t1)
// diff is a time.Duration that you can do stuff with
// ...
5 Likes
elithrar
(Matt Silverlock)
April 3, 2016, 3:45pm
#4
The “vars” are structs: a variable has a type. time.Time
is defined as a struct.
If you want to determine whether a time is before/after another time, you can use time.After
(or Before
) to do this.
e.g.
package main
import "time"
func main() {
now := time.Now()
tomorrow := now.Add(time.Hour * 24)
if tomorrow.After(now) {
// Is after!
} else {
// is the same instant or before
}
}
3 Likes
dugwill
(Dugwill)
April 4, 2016, 2:00pm
#5
Thanks for the the help. Lots of options. The time.After/Before is especially elegant. Its goona take me a while to find all the gems in Go.
system
(system)
closed
July 3, 2016, 2:07pm
#6
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.