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.
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
No comments:
Post a Comment