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

time.RFC3339 #566

Open
jc-fireball opened this issue Sep 3, 2024 · 4 comments
Open

time.RFC3339 #566

jc-fireball opened this issue Sep 3, 2024 · 4 comments
Labels
question Further information is requested

Comments

@jc-fireball
Copy link

Hi

We've been migrating to huma. We notice the default time format is using RFC3339nano in json response. Is there anyway we can set the time format in json to time.RFC3339

@danielgtaylor danielgtaylor added the question Further information is requested label Oct 8, 2024
@danielgtaylor
Copy link
Owner

danielgtaylor commented Oct 8, 2024

@jc-fireball sorry for the slow response on this! The Go JSON marshaler controls this behavior via the time.Time type's MarshalJSON method. See https://pkg.go.dev/time#Time.MarshalJSON and the official implementation at https://cs.opensource.google/go/go/+/refs/tags/go1.23.2:src/time/time.go;l=1392.

You should be able to create a custom type wrapping time.Time that implements custom marshaling as explained at https://stackoverflow.com/questions/23695479/how-to-format-timestamp-in-outgoing-json. If you can't use custom types then you may have to wrap the JSON marshaler itself in the huma.Config formats to special case certain behaviors.

@jc-fireball
Copy link
Author

As you just point out, the Golang default time.Time marshal is using RFC3339, however Huma default to RFC3339Nano

image

@jc-fireball
Copy link
Author

Only the time.Time in header is in different way which allows us to override the format but not in other places like json field.

@danielgtaylor
Copy link
Owner

@jc-fireball that specific code you linked to is Huma's custom handling of parameters (path/query/header/cookie). You can change that time format like this using Go's time formatting:

type MyInput struct {
  MyTime time.Time `query:"myTime" timeFormat:"..."`
}

Keep in mind though this is not for the JSON body, which is controlled by the encoding/json package instead of Huma itself which I linked to above. This is just how Go works with JSON encoding, but you can preprocess times to get the output you want, for example:

t := time.Now()
t = t.Add(123 * time.Millisecond)
b, _ := json.Marshal(t)
fmt.Println(string(b)) // prints with milliseconds

t = t.Truncate(time.Second)
b, _ = json.Marshal(t)
fmt.Println(string(b)) // prints without milliseconds

https://go.dev/play/p/ayaM260jpFQ

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

No branches or pull requests

2 participants