Check If a Date is in The Future? (original) (raw)
Written byEdd Turtle on gophercoding.com
on 13th of November 2023
(Updated: 17th of January 2024)
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.
How to
If you check the date in question, is after the current time then this basically does a ‘am I in the future’ check.
| 1 2 3 | if myDate.After(time.Now()) { fmt.Println("Comparing Dates: My date is in the future") } |
|---|
| 1 2 3 | if myDate.Before(time.Now()) { fmt.Println("Comparing Dates: My date is in the past") } |
|---|
We’ll show a complete example below.
Full Example
This is a kitchen-sink example, where we chuck in a few examples. First we create 2 dates to work with, a future and a past one. We then:
- Compare dates using
After() - Use a function to help tidy the logic
- Show a past-date example
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | package main import ( "fmt" "time" ) func main() { // 48 hours from now futureDate := time.Now().UTC().Add(48 * time.Hour) pastDate := time.Now().UTC().Add(-48 * time.Hour) // Without a function if futureDate.After(time.Now().UTC()) { fmt.Println("(1) Calling gophers of the future") } // Using our helper function if isDateInTheFuture(futureDate) { fmt.Println("(2) The date is in the future!") } else { fmt.Println("(2) The date is not in the future.") } // Past date example if pastDate.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). func isDateInTheFuture(myDate time.Time) bool { return myDate.After(time.Now().UTC()) } |
|---|
Example In Action


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.