Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby get Time in given timezone

Tags:

timezone

ruby

In ruby, how can I get current time in a given timezone? I know the offset from UTC, and want to get the current time in the timezone with that offset.

like image 661
ashweta Avatar asked May 28 '10 06:05

ashweta


People also ask

What is time now in Ruby?

Ruby | Time now() function The now() is an inbuilt method in Ruby returns the current time.


2 Answers

A simpler, more lightweight solution:

Time.now.getlocal('-08:00') Time.now.getlocal(-28800) 

Well documented here.

Update 2021.12.23: If you've got a tzdata timezone name like 'US/Pacific' instead of an offset and you're willing to pull in the tzinfo gem, you could also do this (with thanks to both @chadoh and @kevin from below):

require 'tzinfo'  TZInfo::Timezone.get('US/Pacific').now 

Not really the problem as posed, but maybe helpful to folks in the future.

If you want to do this for moments other than #now, you should study up on the Ruby Time class, particularly Time#gm and Time#local, and the Ruby TZInfo classes, particularly TZInfo::Timezone.get and TZInfo::Timezone#period_for_local

like image 125
Jim Meyer Avatar answered Sep 19 '22 00:09

Jim Meyer


I'd use the ActiveSupport gem:

require 'active_support/time' my_offset = 3600 * -8  # US Pacific  # find the zone with that offset zone_name = ActiveSupport::TimeZone::MAPPING.keys.find do |name|   ActiveSupport::TimeZone[name].utc_offset == my_offset end zone = ActiveSupport::TimeZone[zone_name]  time_locally = Time.now time_in_zone = zone.at(time_locally)  p time_locally.rfc822   # => "Fri, 28 May 2010 09:51:10 -0400" p time_in_zone.rfc822   # => "Fri, 28 May 2010 06:51:10 -0700" 
like image 25
glenn jackman Avatar answered Sep 17 '22 00:09

glenn jackman