Search code examples
gostrftime

time format converted to strftime default format


In the wikipedia entry for Common Log Format, the strftime format is given as:

[10/Oct/2000:13:55:36 -0700] is the date, time, and time zone that the request was received, by default in strftime format %d/%b/%Y:%H:%M:%S %z.

When I try using the time.Format function:

package main

import (
    "fmt"
    "time"
)

func main() {
    t, _ := time.Parse(time.UnixDate, "Tue Oct 10 13:55:36 PDT 2000")
    fmt.Println(time.Time(t).Format("01/Feb/2006:15:04:05 -0700"))
}

I get the output [10/Feb/2000:13:55:36 +0000], while I was expecting [10/Oct/2000:13:55:36 -0700] (per Wikipedia). What is wrong with my formatting?

I checked that day was a Tuesday and the time zone was -7h (PDT) for that date.


Solution

  • For the Format layout, Jan not Feb. For example,

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        t, err := time.Parse(time.UnixDate, "Tue Oct 10 13:55:36 PDT 2000")
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(time.Time(t).Format("01/Jan/2006:15:04:05 -0700"))
    }
    

    Output:

    10/Oct/2000:13:55:36 +0000
    

    Also, for the time zone, use ParseInLocation,

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        loc, err := time.LoadLocation("America/Los_Angeles")
        if err != nil {
            fmt.Println(err)
            return
        }
        t, err := time.ParseInLocation(time.UnixDate, "Tue Oct 10 13:55:36 PDT 2000", loc)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(t)
        fmt.Println(time.Time(t).Format("01/Jan/2006:15:04:05 -0700"))
    }
    

    Playground: https://play.golang.org/p/tBLw5oJSE5t

    Output:

    2000-10-10 13:55:36 -0700 PDT
    10/Oct/2000:13:55:36 -0700