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
+8.4k Golang : Ackermann function example
+7.9k Golang : Grayscale Image
+32.9k Golang : How to check if a date is within certain range?
+14k Javascript : Prompt confirmation before exit
+14.2k Golang : How to convert a number to words
+6.3k Golang : Detect face in uploaded photo like GPlus
+32.1k Golang : Convert []string to []byte examples
+8.1k Golang : Get final or effective URL with Request.URL example
+29.1k Golang : missing Git command
+12.6k Golang : Remove or trim extra comma from CSV
+7k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+8.9k Golang : What is the default port number for connecting to MySQL/MariaDB database ?