Check If a Date is in The Future?

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.

View Time Docs  

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

is date in future in golang