Golang : Convert date or time stamp from string to time.Time type
Problem :
You have dates or time stamps in string format(usually from database) and you want to convert them into time.Time
type. How to do that?
Solution :
Use time.Parse()
function to convert dates or time stamps from string format to time.Time
type.
For example :
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)
year, month, day := timeStamp.Date()
fmt.Printf("Date : [%d]year : [%d]month : [%d]day \n", year, month, day)
}
Sample output :
Clock : [19]hour : [54]minutes : [0] seconds
Date : [2014]year : [12]month : [29]day
See also : Golang : Convert Unix timestamp to UTC timestamp
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
+12.8k Golang : Exit, terminating or aborting a program
+5.1k Python : Find out the variable type and determine the type with simple test
+8.5k Golang : Count leading or ending zeros(any item of interest) example
+8.4k Prevent Write failed: Broken pipe problem during ssh session with screen command
+10.4k Golang : How to profile or log time spend on execution?
+10.2k Golang : Channels and buffered channels examples
+11k Golang : Sieve of Eratosthenes algorithm
+7.2k Golang : Validate credit card example
+21k Android Studio : AlertDialog and EditText to get user string input example
+10.1k CodeIgniter : Load different view for mobile devices
+7k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+6.7k Unix/Linux : How to get own IP address ?