pdoherty926 pdoherty926 - 5 months ago 23
Ruby Question

How can I programmatically change an RFC3339 timezone offset in Ruby?

I'm wondering how I can programmatically change an RFC3339 DateTime's timezone offset in Ruby 2.3 (ActiveSupport is available, if that'd help).

I'd like to convert:

2016-06-22T00:00:00+00:00
into
2016-06-22T00:00:00-04:00
without resorting to string substitution.

EDIT: Per the Tin Man's request, I'll elaborate on what I've tried. As alluded to above, I tried using
gsub
to find-and-replace the offending section of the original string. That worked, but I considered it to be a kludgy solution and wanted to find a solution that made use of the Time/Date API.

Answer

Have a look at DateTime#change, you can pass in an offset.

require 'active_support/core_ext/date_time'

DateTime.now.change(offset: '-0400')
#=> Wed, 22 Jun 2016 23:47:34 -0400