Time and Dates in Go
The time package is essential to managing dates, timings, and durations in Go. In addition to managing time zones, it has extensive features for getting the current time, formatting and parsing time strings, and carrying out time-based computations.
Key ideas are explained here, along with examples of how to use them in code:
Getting the Current Time
The time can be used to get the local time right now.Now() function. The Unix() method on a time can be used to obtain the Unix epoch time, which is the number of seconds that have passed since January 1, 1970 UTC.object of time.
Code Example:
package main
import (
"fmt"
"time"
)
func main() {
// Get the current local time
currentTime := time.Now()
fmt.Println("Current time:", currentTime)
// Get the Unix epoch time
epochTime := currentTime.Unix()
fmt.Println("Epoch time (seconds since Jan 1, 1970 UTC):", epochTime)
}
Output
Current time: 2025-08-18 14:03:33.842858844 +0000 UTC m=+0.000030020
Epoch time (seconds since Jan 1, 1970 UTC): 1755525813
Formatting Dates and Times
Go has a unique way of parsing and presenting times and dates. Unlike other languages, which utilise abstract format codes (such as YYYY-MM-DD), Go defines the desired layout using a reference time. This reference time, with an offset of -0700 (MST), is always January 2, 2006, at 3:04:05 PM (15:04:05). The format of the output is determined by the location of each value in the string, which is supplied to the Format() method.
The time package additionally offers predefined layout constants, such as time, for convenience.Time for RFC3339.Time for RFC1123.Time, stamp.850 RFC.
Code Example:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
// Using a custom format string based on the reference time (Jan 2, 2006 15:04:05)
// "01" for month number, "January" for full month name, "2006" for year, etc.
customFormat := t.Format("01 January 2006, 15:04:05")
fmt.Println("Custom Formatted:", customFormat)
// Using a predefined RFC3339 constant
rfc3339Format := t.Format(time.RFC3339)
fmt.Println("RFC3339 Formatted:", rfc3339Format)
}
Output
Custom Formatted: 08 August 2025, 14:04:05
RFC3339 Formatted: 2025-08-18T14:04:05Z
Parsing Strings into Dates and Times
To translate a time into a string representation of a date and time.You utilize time as an object.The Parse() function. This function accepts two inputs:
- The layout string makes use of the same reference time components as Format().
- The time to be parsed is contained in the string.
Time.time
parsed is returned by Parse().an error and a time object. To guarantee successful parsing, it is imperative to verify this error.
Code Example:
package main
import (
"fmt"
"time"
)
func main() {
// Example 1: Parsing a time string (hour:minute)
timeString := "12:10"
// The layout "15:04" corresponds to "3:04 PM" from the reference time
parsedTime, err := time.Parse("15:04", timeString)
if err == nil {
fmt.Println("Parsed Time (full Time.Time object):", parsedTime) // Default date part added
fmt.Println("Hour:", parsedTime.Hour(), "Minute:", parsedTime.Minute())
} else {
fmt.Println("Error parsing time:", err)
}
fmt.Println("---")
// Example 2: Parsing a date string
dateString := "20 July 2000"
// The layout "02 January 2006" corresponds to "January 2, 2006" from the reference time
parsedDate, err := time.Parse("02 January 2006", dateString)
if err == nil {
fmt.Println("Parsed Date (full Time.Time object):", parsedDate) // Default time part added
fmt.Println("Day:", parsedDate.Day(), "Month:", parsedDate.Month(), "Year:", parsedDate.Year())
} else {
fmt.Println("Error parsing date:", err)
}
}
Output
Parsed Time (full Time.Time object): 0000-01-01 12:10:00 +0000 UTC
Hour: 12 Minute: 10
---
Parsed Date (full Time.Time object): 2000-07-20 00:00:00 +0000 UTC
Day: 20 Month: July Year: 2000
Time Calculations and Durations
The time is provided by Go.Time periods are represented by the duration type. Time and other constants can be used to generate durations.The second is time.It’s time, minute.hour as well as their multiples.
time.Add(duration)
: Adds a minute.duration of a period.Moments.
time.Sub(otherTime)
: Computes the time.length of time between two periods.Time is an arbitrary concept.
time.Sleep(duration)
: The current goroutine’s execution is paused for the provided amount of time. Simulating delays or waiting for concurrent operations are common uses for this.
Code Example:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("Current time:", now)
// Add 24 hours to the current time to get "tomorrow"
tomorrow := now.Add(24 * time.Hour)
fmt.Println("Tomorrow (after adding 24 hours):", tomorrow)
// Calculate the duration between two times
durationDiff := tomorrow.Sub(now)
fmt.Println("Duration difference:", durationDiff)
// Pause execution for a specified duration
fmt.Println("Sleeping for 2 seconds...")
time.Sleep(2 * time.Second)
fmt.Println("Awake after 2 seconds!")
}
Output
Current time: 2025-08-18 14:05:03.926058106 +0000 UTC m=+0.000045098
Tomorrow (after adding 24 hours): 2025-08-19 14:05:03.926058106 +0000 UTC m=+86400.000045098
Duration difference: 24h0m0s
Sleeping for 2 seconds...
Awake after 2 seconds!
Time Zones
Working with several geographic time zones is possible with the time package. With time, you can load a specified place.After loading the location (name string), an existing time is converted.Using the In(loc *Location) method, time is assigned to that location’s time.
Code Example:
package main
import (
"fmt"
"time"
)
func main() {
utcTime := time.Date(2023, time.October, 26, 10, 0, 0, 0, time.UTC)
fmt.Println("UTC Time:", utcTime)
// Load a specific time zone location (e.g., "America/New_York" or "Europe/Paris")
parisLocation, err := time.LoadLocation("Europe/Paris")
if err != nil {
fmt.Println("Error loading Paris location:", err)
return
}
// Convert the UTC time to Paris time
parisTime := utcTime.In(parisLocation)
fmt.Println("Paris Time:", parisTime)
// You can also get the current system's local time zone
localTime := time.Now()
fmt.Println("Local System Time:", localTime)
}
Output
UTC Time: 2023-10-26 10:00:00 +0000 UTC
Paris Time: 2023-10-26 12:00:00 +0200 CEST
Local System Time: 2025-08-18 14:05:33.347329518 +0000 UTC m=+0.000331815
Specialized Use Cases
init()
function: Utilizing time is possible with the unique init() function, which executes before main().For example, you can set a weekday variable to the current day of the week by using Now() to initialise it with the current date or time.
Concurrency with select and time.After(): The select statement can be used in conjunction with time in concurrent programming.To implement timeouts, use After().A select case can be triggered if a timeout happens before other channel activities since After() returns a channel that delivers a value after the given duration.
HTTP Server/Client Timeouts: The moment.HTTP clients and servers can set timeout durations for network operations using the Duration type. To limit the amount of time that can be spent reading requests and writing responses, for example, http.Server can have ReadTimeout and WriteTimeout, while http.Client can have a Timeout for its requests.
You can also read Error Handling In GoLang: Chaining Errors for Better Debug