Convert UTC string to time object

后端 未结 3 832
终归单人心
终归单人心 2020-12-06 19:00

I have this datetime, or something that looks like it.

2014-11-17 23:02:03 +0000 UTC

I want to convert this to a time object and I\'ve been

3条回答
  •  攒了一身酷
    2020-12-06 19:33

    Most likely you used a wrong layout, and you didn't check the returned error.

    The layout must be this date/time, in the format your input time is:

    Mon Jan 2 15:04:05 -0700 MST 2006
    

    See this working code:

    layout := "2006-01-02 15:04:05 -0700 MST"
    t, err := time.Parse(layout, "2014-11-17 23:02:03 +0000 UTC")
    fmt.Println(t, err)
    

    Output (try it on the Go Playground):

    2014-11-17 23:02:03 +0000 UTC 
    

    EDIT:

    In your question you included a + sign in your input time (as part of the zone offset), but you have error with times of other formats.

    Time.String() uses the following format string:

    "2006-01-02 15:04:05.999999999 -0700 MST"
    

    So either use this to parse the times, or use Time.Format() to produce your string representations where you can specify the layout, so you can use the same layout to parse the time strings.

    2nd round:

    You're including your time strings in URLs. The + sign is a special character in URL encoding: it denotes the space. So the + gets converted to space (and so it vanishes from your time string). Use proper URL encoding! Check out the net/url package, and this example.

提交回复
热议问题