Formatting in RFC3339 of Golang’s time

Today in development, I found that when converting time to json, the time will be converted to RFC3339 format by default

2018-01-14T21:45:54+08:00

Let’s take a look at the constant definition of the format in the time package

const (
ANSIC = "Mon Jan _2 15:04:05 2006"
UnixDate = "Mon Jan _2 15:04:05 MST 2006"
RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
RFC822 = "02 Jan 06 15:04 MST"
RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
RFC3339 = "2006-01-02T15:04:05Z07:00"
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
Kitchen = "3:04PM"
// Handy time stamps.
Stamp = "Jan _2 15:04:05"
StampMilli = "Jan _2 15:04:05.000"
StampMicro = "Jan _2 15:04:05.000000"
StampNano = "Jan _2 15:04:05.000000000"
)

cut to the chase
how to take this time
2018-01-14T21:45:54+08:00
convert to
2018-01-14 21:45:54

In fact, after thinking about the method, it is still very simple

str:="2018-01-14T21:45:54+08:00"//Convert the time to a string first
tt,_:=time.Parse("2006-01-02T15:04:05Z07:00",str)
//format time
fmt.Println(tt.Format("2006-01-02 15:04:05"))

get the time you want
The layout parameter of time.Parse() is the RFC3339 defined by the above constants
If you have other formats, just copy the corresponding layout.
tt.Format()
is to format the time in a custom way
2006-01-02 15:04:05 here must not change

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish