Format timestamps for JSON payload

What’s the recommended way to format timestamps coming out of the db? For example, I’d like all timestamps to be formatted as ISO 8601 when they are sent down the wire in a JSON payload.

Hi and welcome :smile:

You could use a custom type for this:

JSONTime = ROM::Types::String.constructor { |time|
  time.strftime('%Y-%m-%dT%H:%M:%S.%L%z')
}

# then in relation schema:

schema(infer: true) do
  attribute :your_time_col, Types::Time, read: JSONTime
end

Notice that this assumes that input values are sent as time objects, if you want to pass strings and have them coerced to time, you need to use another custom type.

Hope this helps.

1 Like

We also use custom yours for this, using time.iso8601

1 Like

@solnic Your solution worked in v4, but appears to no longer work with v5. After looking through the changes in rom and dry-types, I’m not seeing what needs to be updated. Help?

@mdi please report an issue with a reproduction script and I’ll look into it

Scratch that. It does work. My mistake.