contact411
contact411

Reputation: 105

Converting time between timezone without changing the time?

Our system currently defaults to Sydney time. I'm attempting to localize some reports to another timezone without changing the daily interval of the reports (i.e. 00:00:00 to 23:59:59).

Any time I attempt to convert the time object to another time zone it converts the hour/minutes/seconds along with the zone.

[16] pry(main)> t = Time.now
=> 2015-09-07 14:41:33 +1000

[17] pry(main)> t.in_time_zone("Darwin")
=> Mon, 07 Sep 2015 14:11:33 ACST +09:30

Can someone please point me in the right direction?

Thanks!

Upvotes: 1

Views: 537

Answers (3)

Stefan
Stefan

Reputation: 114138

You can use Time::use_zone to override the time zone inside a given block:

t = Time.parse('2015-09-07 14:41:33 +1000')
#=> 2015-09-07 14:41:33 +1000

Time.use_zone('Darwin') { Time.zone.local(t.year, t.month, t.day, t.hour, t.min, t.sec) }
#=> Mon, 07 Sep 2015 14:41:33 ACST +09:30

Or the shortcut:

Time.use_zone('Darwin') { Time.zone.local(*t) }
#=> Mon, 07 Sep 2015 14:41:33 ACST +09:30

*t converts t to an array (using Time#to_a) and passes its elements as arguments:

The ten elements can be passed directly to ::utc or ::local to create a new Time object.

Upvotes: 3

pguardiario
pguardiario

Reputation: 54984

Maybe with regex is the most straightforward way:

t = Time.now
#=> 2015-09-07 05:53:23 +0000
Time.parse t.to_s.sub(/[+-]\d+$/, '+0930')
#=> 2015-09-07 05:53:23 +0930

Upvotes: 1

contact411
contact411

Reputation: 105

I've found a solution.. Please feel free to leave an any answers that would be better as I am still a lowly junior.

I created the following method:

def export_in_timezone(time, zone)
  Time.use_zone(zone) { time.to_datetime.change(offset: Time.zone.now.strftime("%z")) }
end

and pass in the time and timezone for each reporting being created.

Thanks!

Upvotes: 0

Related Questions