Home > Net >  How to format time.Time datatype in struct in Go?
How to format time.Time datatype in struct in Go?

Time:02-12

I want my time.Time in struct accept my JSON input from Postman in formatted date ("yyyy-mm-dd")

I have this struct

type Transaction struct {
    Id_transaction        string                `gorm:"primary_key;type:varchar(255)" json:"id_transaction"`
    Due_date              time.Time             `json:"due_date"`
}

And I want to send JSON data for the due_date like

{
        "due_date" : "2022-02-11"
}

also I'm using GIN and GORM and catch the input using DTO like this

type TransactionCreateDTO struct {
    Id_transaction        string                `json:"id_transaction" form:"id_transaction"`
    Due_date              time.Time             `json:"due_date" form:"due_date"`
}

var transactionDTO dto.Transaction
context.ShouldBind(&transactionDTO)

But the format didn't match and I got error. How can I make the time.Time in my Transaction struct accept my input time format?

CodePudding user response:

By default golangs time.Time expects a certain format for time which is 2006-01-02T15:04:05Z07:00 or RFC3339.

Take a look at this lib https://github.com/efimovalex/odt. It implements a json decoder for date format (also an mysql driver encoder for date).

If you want your own implementation You need to implement your own Date struct with a custom UnmarshalJSON method

You can also take a look at this article

CodePudding user response:

The simple answer is to use the format method which is defined on time.

time.Now().Format("2006-04-02") \\2022-02-12

here 2006-04-02 is just time.Now().Format("YYYY-MM-DD") done by go to have some preview.

another example

time.Now().Format("2006-04-02") \\2022-59-12 00:59:28
  • Related