How to Use time.Time.Before() Function in Golang

Golang Time.Before() function is “used to check if the stated time instant t is before the stated u.”

Syntax

func (t Time) Before(u Time) bool

Parameters

  1. t: It is the stated time.
  2. u: It is the time present as an argument in the Before() method.

Return value

It returns true if “t” is present before “u”; else, it returns false.

Example 1: How to Use Time.Before() function

package main

import (
  "fmt"
  "time"
)

func main() {
  // Define two dates
  date1 := time.Date(2023, 7, 1, 0, 0, 0, 0, time.UTC)
  date2 := time.Date(2024, 7, 1, 0, 0, 0, 0, time.UTC)

  // Check if date1 is before date2
  if date1.Before(date2) {
    fmt.Println("July 1, 2023 is before July 1, 2024.")
  } else {
    fmt.Println("July 1, 2023 is not before July 1, 2024.")
  }
}

Output

July 1, 2023 is before July 1, 2024.

Example 2: Check if now is before one hour later

package main

import (
  "fmt"
  "time"
)

func main() {
  // Get the current time
  now := time.Now()

  // Get the time 1 hour from now
  oneHourLater := now.Add(1 * time.Hour) 

  // Check if now is before oneHourLater
  if now.Before(oneHourLater) {
    fmt.Println("Now is before one hour later.")
  } else {
    fmt.Println("Now is not before one hour later.")
  }
}

Output

Now is before one hour later.

That’s it.