Sard
Sard

Reputation: 2385

Date parsing in Go

I'm trying to parse a timestamp as produced by tar such as '2011-01-19 22:15' but can't work out the funky API of time.Parse.

The following produces 'parsing time "2011-01-19 22:15": month out of range'

package main
import (
    "fmt"
    "time"
    )

func main () {
    var time , error = time.Parse("2011-01-19 22:15","2011-01-19 22:15")
    if error != nil {
        fmt.Println(error.String())
        return
        }
    fmt.Println(time)
    }

Upvotes: 21

Views: 23820

Answers (1)

peterSO
peterSO

Reputation: 166549

Follow the instructions in the Go time package documentation.

The standard time used in the layouts is:

Mon Jan 2 15:04:05 MST 2006 (MST is GMT-0700)

which is Unix time 1136243045. (Think of it as 01/02 03:04:05PM '06 -0700.) To define your own format, write down what the standard time would look like formatted your way.

For example,

package main

import (
    "fmt"
    "time"
)

func main() {
    t, err := time.Parse("2006-01-02 15:04", "2011-01-19 22:15")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(time.SecondsToUTC(t.Seconds()))
}

Output: Wed Jan 19 22:15:00 UTC 2011

Upvotes: 39

Related Questions