Reputation: 6289
I want to convert time by passing time with timezone for conversion.
Writing a single method which convert time with timezone.
Time.now + Time.zone_offset("PST")
Will it work ?
i need a method in ruby.
Upvotes: 1
Views: 10255
Reputation: 241525
"PST" only represents the part of the Pacific time zone that falls into Pacific Standard Time. To fully represent the time zone, you must consider Pacific Daylight Time also.
To do this in Ruby, you should use the tzinfo gem, as follows:
require 'tzinfo'
tz = TZInfo::Timezone.get('America/Los_Angeles')
now = tz.now
See also "Time Zone != Offset" in the timezone tag wiki.
Upvotes: 4
Reputation: 10251
Have a look at in_time_zone
> Time.zone = 'Hawaii'
=> "Hawaii"
> DateTime.now.in_time_zone
=> Mon, 03 Nov 2014 04:00:29 HST -10:00 # UTC-10:00
> DateTime.now
=> Mon, 03 Nov 2014 19:30:41 +0530 # UTC+05:30
> Time.zone = "Eastern Time (US & Canada)"
=> "Eastern Time (US & Canada)"
> DateTime.now.in_time_zone
=> Mon, 03 Nov 2014 09:03:34 EST -05:00
Upvotes: 1
Reputation: 118271
No direct method is present. But you can solve it as
>> a = %w(%Y %m %d %H %M %S)
=> ["%Y", "%m", "%d", "%H", "%M", "%S"]
>> tm = Time.now
=> 2014-11-03 17:46:02 +0530
>> a.map { |s| tm.strftime(s) }
=> ["2014", "11", "03", "17", "46", "02"]
>> a.map! { |s| tm.strftime(s).to_i }
=> [2014, 11, 3, 17, 46, 2]
>> Time.new(*a, Time.zone_offset('PST'))
=> 2014-11-03 17:46:02 -0800
Look at the new(year, month=nil, day=nil, hour=nil, min=nil, sec=nil, utc_offset=nil) → time
documentation. utc_offset
for PST is -08:00
.
Upvotes: 0
Reputation: 16002
There's no method for that, however you can make one for yourself:
class Time
require 'time'
def self.by_offset(offset)
at(now + zone_offset(offset))
end
end
Now, you can:
Time.by_offset('PST')
#=> 2014-11-03 10:11:14 +0530
Time.now
#=> 2014-11-03 18:11:13 +0530
Tested with 1.9.2, 2.0.0, and 2.1.2 Rubies(MRI).
Upvotes: 3