Golang 2018-06-how to convert 06T20:14:03.368+0800 to unix timestamp

golang 2018-06-06T20:14:03.368+0800 how to convert to unix timestamp
tried several ways to almost cry

Mar.20,2021

the time format of golang really bothers newcomers, and it takes a little time to get used to it.

all you need to do here is to call time.Parse () , and then read the time.Unix () result.
the time format should be "2006-01-02T15:04:05.999-0700". Please refer to the following example

package main

import (
    "fmt"
    "testing"
    "time"
)

func TestParseTime(t *testing.T) {
    str := "2018-06-07T20:14:03.368+0800"

    format := "2006-01-02T15:04:05.999-0700"
    tm, err := time.Parse(format, str)
    if err != nil {
        t.Fatal(err)
    }
    _, zoffset := tm.Zone()
    if tm.Year() != 2018 || tm.Month() != 6 || tm.Day() != 7 || tm.Hour() != 20 || tm.Minute() != 14 || tm.Second() != 3 || zoffset != 8*3600 {
        t.Fatal(tm)
    }
    fmt.Println(tm.Unix())
}

try this

package main

import (
    "fmt"
    "time"
)

func main() {
    const layout = "2006-01-02T15:04:05.999999999+0800"
    t, err := time.Parse(layout, "2018-06-06T20:14:03.368+0800")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(t.Unix())
}
Menu