Whether you’re setting up a calendar event or issuing a JWT token, knowing how to manipulate and validate time can save you from many potential headaches. In Go, the built-in time package provides a comprehensive set of tools to work with dates and times.
packagemainimport("fmt""time")funcmain(){// 48 hours from now
futureDate:=time.Now().UTC().Add(48*time.Hour)pastDate:=time.Now().UTC().Add(-48*time.Hour)// Without a function
iffutureDate.After(time.Now().UTC()){fmt.Println("(1) Calling gophers of the future")}// Using our helper function
ifisDateInTheFuture(futureDate){fmt.Println("(2) The date is in the future!")}else{fmt.Println("(2) The date is not in the future.")}// Past date example
ifpastDate.Before(time.Now().UTC()){fmt.Println("(3) I'm from the past...")}}// isDateInTheFuture checks if a given date is greater than now (is in the
// future based on UTC timezone).
funcisDateInTheFuture(myDatetime.Time)bool{returnmyDate.After(time.Now().UTC())}
Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.