In Go, we have the “time” package which comes packed with lots of tools and features to work with time related operations including timestamps.
In this tutorial, we will learn about datetime and how to work with them in Go without using the external packages.
What Is Datetime?
Datetime refers to the combination of date (calendar date) and time (clock time) information. It includes details such as the year, month, day, hour, minute, second, and timezone offset.
Create a Datetime in Go
In Go, we can create a datetime using the time.Now() function which returns the current time in the local timezone.
An example is as follows:
import (
"fmt"
"time"
)
func main() {
currentTime := time.Now()
fmt.Println("Current Time:", currentTime)
}
This should return the current time and print it to the console. The function uses the time zone that is configured in the current device.
Example Output:
Formatting the Datetime
We can also format the datetime to follow specific layouts which are very useful in consistency and template.
We can use the layout constants like “2006-01-02 15:04:05” to define the desired format. Consider an example as follows:
import (
"fmt"
"time"
)
func main() {
currentTime := time.Now()
formattedTime := currentTime.Format("2006-01-02 15:04:05")
fmt.Println("Formatted Time:", formattedTime)
}
Resulting Output:
Parsing the Datetime
To convert a string into a datetime, we can use the “time.Parse” function, specifying the layout that matches the input string.
import (
"fmt"
"time"
)
func main() {
inputTime := "2023-11-30 10:41:59"
parsedTime, err := time.Parse("2006-01-02 15:04:05", inputTime)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Parsed Time:", parsedTime)
}
}
The resulting output is as follows:
Setting the Time Zones
We can also specify the target time zone without actually modifying the time zone of the host machine.
We can use the “time.LoadLocation” function to obtain a “time.Location” value that represents a specific time zone and then set it for a datetime.
import (
"fmt"
"time"
)
func main() {
loc, _ := time.LoadLocation("America/New_York")
currentTime := time.Now().In(loc)
fmt.Println("Current Time in New York:", currentTime)
}
Output:
This returns the current time in the specified location.
Conclusion
In this tutorial, we learned how to use and work with datetime in Go by taking advantage of the “time” package and the provided methods.