Search code examples
datetimegotimecouchbasegocb

why format of time changes in JSON binding?


i have created a struct and it contains two time.Time formatted fields, named with json tags: start_time and end_time.

type MyStruct struct {

   StartTime  time.Time `json:"start_time"`
   EndTime    time.Time `json:"end_time"`
}

when i'm trying to send a PUT request over HTTP using gin framework to update those values, the time format which i'm sending, changes in sent struct. what i'm sending:

curl    -X  PUT   -H  'Content-Type: application/json'
http://my_address -d '{
"start_time": "2021-04-27T22:24:31Z",
"end_time": "2021-11-01T22:24:31Z"
}'

what it receives:

start_time="2021-04-27 22:24:31 +0000 UTC",
end_time="2021-11-01 22:24:31 +0000 UTC",

in the other hand, i'm saving the struct in a couchbase and as returning value of query, i'm sending back the document(my struct):

my query:

Update BucketName as e
set start_time="2021-04-27 22:24:31 +0000 UTC",
end_time="2021-11-01 22:24:31 +0000 UTC" where ( my document equality condition)
returning e

and it executes with no errors. when i'm trying to read the returned struct,

my code to reading it:

var s domain.MyStructSample //                                                                                                               
    err = result.One(&s)
    if err != nil { 
     if err == gocb.ErrNoResult {
        return nil, errors.New("there is no result")
      }
      logger.ZSLogger.Errorf("error on update one item from my struct with error :%s", err)
      return nil, err
    }
      

gocb generates errors on those time items and here is the error:

"message":"error on update one item from my struct  with error :parsing time \"\"2021-11-01 22:24:31 +0000 UTC\"\" as \"\"2006-01-02T15:04:05Z07:00\"\": cannot parse \" 22:24:31 +0000 UTC\"\" as \"T\""}

by the way, as i said, update is done with no errors ( query executes with no errors). so what should i do with it ?


Solution

  • How did you generate this query:

    Update BucketName as e
    set start_time="2021-04-27 22:24:31 +0000 UTC",
    end_time="2021-11-01 22:24:31 +0000 UTC" where ( my document equality condition)
    returning e
    

    As the error says, time data stored in couchbase should be in format RFC3339 (2006-01-02T15:04:05Z07:00) instead of the default 2006-01-02 15:04:05 -0700 MST, so maybe you should insert data with query:

    Update BucketName as e
    set start_time="2021-04-27T22:24:31Z07:00",
    end_time="2021-11-01T22:24:31Z07:00" where ( my document equality condition)
    returning e
    

    If you have problem formatting time, read the doc https://golang.cafe/blog/golang-time-format-example.html

    And, as @MrFuppes commented, if you need to customize JSON output format, read this How to format timestamp in outgoing JSON