Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How Can I BindJson With time_format #2681

Open
figoxu opened this issue Apr 9, 2021 · 2 comments
Open

How Can I BindJson With time_format #2681

figoxu opened this issue Apr 9, 2021 · 2 comments

Comments

@figoxu
Copy link

figoxu commented Apr 9, 2021

  • With issues:
    • The Following Code Is Panic
    • It Always Using Default Time Layout "2006-01-02T15:04:05Z07:00"
    • Error Msg is "panic: parsing time ""2022-04-09"" as ""2006-01-02T15:04:05Z07:00"": cannot parse """ as "T" "

Description

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.New()
	w := httptest.NewRecorder()
	jsonBody := `{
		"start_time": "2022-04-09",
		"show_start": "2022-04-09",
		"show_end":   "2022-04-09"
}`
	type Y struct {
		StartTime time.Time `json:"start_time,string"  time_format:"2006-01-02"`
		ShowStart time.Time `json:"show_start,string"  time_format:"2006-01-02"`
		ShowEnd   time.Time `json:"show_end,string"  time_format:"2006-01-02"`
	}
	req, _ := http.NewRequest("GET", "/test", strings.NewReader(jsonBody))
	r.GET("/test", func(c *gin.Context) {
		var y Y
		err := c.BindJSON(&y)
		if err!=nil {
			panic(err)
		}
	})
	r.ServeHTTP(w, req)
	fmt.Println(`Done`)
}

Expectations

$ go run main.go
Done

Environment

  • go version: go1.16.1 darwin/amd64
  • gin version (or commit ref): github.com/gin-gonic/gin v1.5.0
  • operating system: MacOs Catalina 10.15.7
@kszafran
Copy link
Contributor

I believe this is the same question: #1193

@harshalhonmote
Copy link

change the jsonBody date format:
jsonBody := { "start_time": "2022-04-09T15:04:05Z", "show_start": "2022-04-09T15:04:05Z", "show_end": "2022-04-09T15:04:05Z" }
Because time.Time in DB datetime(YYYY-MM-DDTHH:mm:ssZ)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants