Help with if statement

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:\dugwill\\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


you can compare as Unix time

package main


func main(){
t0 := time.Now().Unix()
t1 := time.Now().Unix()
fmt.Println(t1 - t0)



Success: process exited with code 0.

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
// ...

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.


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

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.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.