2

This is maybe a stupid question to ask but I can't seem to find how to convert date in string format to date time format. Many thanks!

s := "12-25-2012"
var t time.Time

t = s.Time() ??? 

I would like t to contain the value of s.

sagit
  • 911
  • 1
  • 8
  • 14

2 Answers2

4

You need time.Parse() and a format string that matches your supplied date string.

Here's an example using your date format.

package main

import (
    "fmt"
    "time"
    )

func main() {
    s := "12-25-2012"
    format_string := "01-02-2006"
    t, err := time.Parse(format_string, s)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%v\n", t)
}

http://play.golang.org/p/YAeAJ3CNqO

You can read more about making custom format strings in this post.

Community
  • 1
  • 1
Daniel
  • 38,041
  • 11
  • 92
  • 73
2

According to this article:

package main

import (
    "fmt"
    "time"
)

func main() {
    value  := "Thu, 05/19/11, 10:47PM"
    // Writing down the way the standard time would look like formatted our way
    layout := "Mon, 01/02/06, 03:04PM"
    t, _ := time.Parse(layout, value)
    fmt.Println(t)
}

// => "Thu May 19 22:47:00 +0000 2011"
CC Inc
  • 5,842
  • 3
  • 33
  • 64