How do I get a Range of ActiveSupport::TimeWithZone from a tstzrange column?

Viewed 270

I have a tstzrange column. Rails is translating it into a Range of Time objects which loses the time zone information. I would like a Range of ActiveSupport::TimeWithZone objects. How can I do that?

Alternatively, how can I check if tstzrange spans exactly a day in the current time zone, and what day?

1 Answers

From the ActiveRecord::Timestamp docs...

You can also add database specific timezone aware types. For example, for PostgreSQL:

ActiveRecord::Base.time_zone_aware_types += [:tsrange, :tstzrange]

in_time_zone will turn a Time into ActiveSupport::TimeWithZone in the application's time zone. A Range of Times can be turned into a Range of ActiveSupport::TimeWithZone like so:

range = Range.new(
  tstzrange.begin.in_time_zone,
  tstzrange.end.in_time_zone,
  # Taking care to preserve whether the range is inclusive or exclusive.
  tstzrange.exclude_end?
)
Related