Golang : How to get hour, minute, second from time?
Problem :
You have unix timestamp or time stamp in string format. You want to convert the unix timestamps from string to time.Time
type and get the hour, minute and second. How to do that?
Solutions :
Use time.Unix()
, time.Parse()
and time.Time.Clock()
functions.
Example 1 - convert Unix time :
package main
import (
"fmt"
"os"
"strconv"
"time"
)
func main() {
unixTimeStamp := "1432572732"
unixIntValue, err := strconv.ParseInt(unixTimeStamp, 10, 64)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
timeStamp := time.Unix(unixIntValue, 0)
//fmt.Println(timeStamp)
hr, min, sec := timeStamp.Clock()
fmt.Printf("Clock : [%d]hour : [%d]minutes : [%d] seconds \n", hr, min, sec)
}
Example 2 - convert time from string to time.Time :
package main
import (
"fmt"
"os"
"time"
)
func main() {
// convert time string to time.Time type
timeStampString := "Dec 29, 2014 at 7:54pm (SGT)"
layOut := "Jan 2, 2006 at 3:04pm (MST)"
timeStamp, err := time.Parse(layOut, timeStampString)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
hr, min, sec := timeStamp.Clock()
fmt.Printf("Clock : [%d]hour : [%d]minutes : [%d] seconds \n", hr, min, sec)
}
See also : Golang : How to get year, month and day?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.6k Golang : Word limiter example
+20.5k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+12k Golang : Get IP addresses of a domain name
+3.7k Golang : Get S3 or CloudFront object or file information
+22.6k Golang : Convert CSV data to JSON format and save to file
+6.8k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+4.1k Golang : How to get capacity of a slice or array?
+6.2k Golang : Write multiple lines or divide string into multiple lines
+6.5k Golang : Play .WAV file from command line
+3.3k Unix/Linux : How to find out the hard disk size?
+27.3k Golang : Validate email address with regular expression
+3.8k Golang : Fixing Gorilla mux http.FileServer() 404 problem