In our previous tutorial, we have explained How to Make HTTP Requests in Golang. In this tutorial, we will explain how to work with Date and Time in Golang.
Date and Time is a common functionality in web applications to display dates in different formats according to requirement. Sometimes we need to get current timestamp or sometimes need to convert timestamp into human readable date time format. In Golang, we can use Time package to handle date time functionality.
Also, read:
Here in this tutorial, we will cover following date time functionality:
1. Get Current Timestamp in Golang
We can easily get the current by using time()
package. We will also use the Unix()
function to get the current Unix timestamp. Here in below example code, we will get the current Unix timestamp.
package main import ( "fmt" "time" ) func main() { currentTimestamp := time.Now().Unix() fmt.Println("Current Timestamp: ", currentTimestamp) }
Output:
Current Timestamp: 1596975790
2. Convert Current Timestamp to Date in Golang
We can easily convert the Unix timestamp to human readable date using time.Unix
function. In below example code, we will convert the Unix timestamp to human readable date.
package main import ( "fmt" "time" ) func main() { currentTimestamp := 1596975790 currentDate := time.Unix(currentTimestamp, 0) fmt.Println("Current Date: ", currentDate) }
Output:
Current Date: 2020-08-09 18:03:30 +0530 IST
3. Convert Date to Timestamp in Golang
We can also easily parse the human readable date into time and convert to Unix timestamp. Here in this example code, we will convert the human readable date to Unix time stamp.
package main import ( "fmt" "time" ) func main() { dateTime, e := time.Parse(time.RFC3339, "2020-08-09T22:08:41+00:00") if e != nil { panic("Parse error") } timestamp := dateTime.Unix() fmt.Println("Date to Timestamp : ", timestamp) }
Output:
Date to Timestamp : 1597010921
You may also like:
- Regular Expressions in Golang
- Creating REST API with Golang
- How to Delete Files in Golang
- Working with Structs in Golang
- How to Make HTTP Requests in Golang
- Working with Channels in Golang
- Concurrency with Goroutines in Golang
- Working with Maps in Golang
- Marshalling and Unmarshalling in Golang
- AWS S3 File Upload in Golang
- Write Data to CSV File using Golang
- How to Read CSV File using Golang
- Parsing JSON Data using Golang
- Read File Line by Line using Golang