Format conversion 0001-01-01T00:00:00Z from time field. Time

Asked

Viewed 174 times

0

I’m using the ORM Gorm for a project, and in the columns referring to the dates, according to documentation, it is necessary to set the type team. Time in Structs fields that abstract dates.

The return of these columns generated by the ORM, comes in the pattern 0001-01-01T00:00:00Z (time.Time type). How exactly can I format this structure for another format like 0001-01-01 00:00:00 and vice versa (turn another format to this one that he is using by default)?

I tried several examples that I found on the Internet, but none of them worked with this specific format, and I didn’t succeed with some dynamics that I saw on some other topics, working with parse of other formats, since I have not found any practical example that has this format.

1 answer

2


If he’s already one time.Time you can "change it" by using your own .Format(). You will only change when displaying the date, in case.


Whereas:

type SeuStruct struct {
    Data time.Time
}

Then just use the seuStruct.Data.Format, as:

func main() {
    // Considerando que o `SeuStruct` fosse o seu struct
    ss := &SeuStruct{Data: time.Now()}

    // Formata como quer exibir:
    fmt.Println(ss.Data.Format("2006-01-02 15:04:05"))
}

The 2006-01-02 15:04:05 define the format, you can see the documentation in https://golang.org/pkg/time/#pkg-constants.

  • Got it! Is there any efficient way for me to standardize this format in the return of a query for example? Because what I think about doing is iterating the entire Slice returned by the query and giving the .Format() in the field that is team.Time, but it does not seem to me efficient that.

  • 1

    If you’re worried about performance at this level, don’t use time.Time first, the conversion already occurs by turning TIME/DATE/TIMESTAMP/DATETIME into time.Time. If you don’t want the conversion to time.Time remove the parseTime=True (or equivalent, when starting the database connection) and use string. You can also use your own DATE_FORMAT() mysql (or equivalent) and return as string, either way conversion will occur. I use time.Time, it also implements the .MarshalJSON and the .GobDecode then the json.Encoder()/gob.Encoder() works directly.

  • Okay, I really appreciate your explanation, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.