Go is a powerful and efficient programming language that is widely used for building modern applications. One of the essential aspects of any programming language is handling time. In this blog, we will discuss how to handle time in Golang.
Working with time in Go is straightforward, as Go provides a standard time library that offers a range of functions for working with dates and times. Let's take a look at some of the most commonly used functions in the time package.
The Time struct
In Go, time is represented using the time.Time struct. The time.Time struct contains several fields that represent the date and time, including the year, month, day, hour, minute, second, and nanosecond.
type Time struct {
wall uint64
ext int64
loc *Location
}
The wall field represents the number of seconds since January 1, 1970, UTC, while the ext field represents the fractional second, and the loc field represents the time zone location.
Getting the current time
The time.Now() function returns the current local time.
currentTime := time.Now()
The time.Now() function returns the current time in the local time zone. If you need to get the current time in a specific time zone, you can use the time.LoadLocation() function to load the time zone.
location, _ := time.LoadLocation("America/New_York")
currentTime := time.Now().In(location)
Formatting time
Go provides a handy function called time.Format() to format time in a particular layout.
currentTime := time.Now()
fmt.Println(currentTime.Format("01-02-2006 15:04:05"))
In the above example, the time.Format() function uses a predefined layout to format the current time in the format of "01-02-2006 15:04:05".
Parsing time
Go provides another handy function called time.Parse() to parse time from a string.
inputTime := "2022-03-07T14:15:16-05:00"
parsedTime, err := time.Parse(time.RFC3339, inputTime)
In the above example, the time.Parse() function uses the time.RFC3339 layout to parse the input time string into a time.Time struct.
Manipulating time
Go provides several functions for manipulating time. For example, you can add or subtract a duration from a time using the time.Add() and time.Sub() functions.
currentTime := time.Now()
futureTime := currentTime.Add(24 * time.Hour)
duration := futureTime.Sub(currentTime)
fmt.Println(duration.Hours())
In the above example, we use the time.Add() function to add 24 hours to the current time and get the future time. We then use the time.Sub() function to get the duration between the current time and the future time. Finally, we use the duration.Hours() function to get the duration in hours.
Conclusion
Handling time in Golang is straightforward, thanks to the time package. In this blog, we discussed some of the most commonly used functions in the time package, such as getting the current time, formatting time, parsing time, and manipulating time. These functions can be used to perform various time-related operations in your Golang applications.