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
- t: It is the stated time.
- 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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.