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
+7.9k Golang : GMail API create and send draft with simple upload attachment example
+8.5k Golang : How to protect your source code from client, hosting company or hacker?
+42.7k Golang : Use wildcard patterns with filepath.Glob() example
+15.3k Golang : Send email and SMTP configuration example
+8.8k Golang : Function wrapper that takes arguments and return result example
+6.1k Golang : Accessing dataframe-go element by row, column and name example
+4.8k Unix/Linux : Get reboot history or check when was the last reboot date
+5.7k Golang : How to setup a disk space used monitoring service with Telegram bot
+8.8k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+20.6k Golang : How to reverse slice or array elements order
+15.1k Golang :Trim white spaces from a string
+9.5k Swift : Convert (cast) String to Integer