Description
i want JSON response for time.TIme format like yyyy-MM-dd hh:mm:ss
How to reproduce
package main
import (
"time"
"github.com/gin-gonic/gin"
)
type InfoData struct {
Id uint `json:"id"`
Tdate time.Time `json:"tdate"`
}
func main() {
gin.Default()
router := gin.Default()
router.POST("/data", func(ctx *gin.Context) {
tracks := make([]*InfoData, 0)
data1 := InfoData{}
data1.Id = 1
data1.Tdate = time.Now()
tracks = append(tracks, &data1)
data2 := InfoData{}
data2.Id = 2
data2.Tdate = time.Now()
tracks = append(tracks, &data2)
ctx.JSON(200, tracks)
})
router.Run(":8080")
}
Expectations
$ curl http://localhost:8080/data
[
{
"id": 1,
"tdate": "2022-07-05 14:07:33.28"
},
{
"id": 2,
"tdate": "2022-07-05 14:07:33.28"
}
]
Actual result
$ curl http://localhost:8080/data
[
{
"id": 1,
"tdate": "2022-07-05T14:07:33.2871003+07:00"
},
{
"id": 2,
"tdate": "2022-07-05T14:07:33.2871003+07:00"
}
]
Environment
- go version:1.18
- gin version (or commit ref):
- operating system: windows 10 , ubuntu 22.04
Comment From: valxntine
Hi @centratelemedia - in order to get the format of datetime you're looking for, you should format your time.Time like so:
time.Now().Format("2006-01-02 15:04:05.12")
An example can be found here: https://go.dev/play/p/62XYrB_ic-Z
Not that the playground has a seeded time so it won't be the datetime you expect in the output so you can try pasting the code from the playground into a local environment and running it.
Hope this helps!
Comment From: centratelemedia
@valxntine
i think gin-goni internally have converter convert from time.Time to custom format, btw, that enought to solve my problem
Comment From: aohanhongzhi
@valxntine
i think gin-goni internally have converter convert from time.Time to custom format, btw, that enought to solve my problem
first, we should use custom json to serialize and deserialize , but I have never found the way to do it.
refer: https://github.com/liamylian/jsontime