3

I have a datestring in this format yyyy-mm-ddThh:mm:ss[Z]

And i have a timezone string. for e.g "Asia/Kolkata"

Now i want to convert this date string into the timezone of the given timezone

for e.g. if the date is 2014-01-03T23:30:00Z , then in "Asia/Kolkata" timezone it will be 2014-01-04T05:00:00 .

I tried using Time library , but Time library does not seem to have any method which can convert to other timzone http://ruby-doc.org/core-1.8.6/Time.html#method-c-mktime .

Phrogz
  • 296,393
  • 112
  • 651
  • 745
Dheeraj Tyagi
  • 31
  • 1
  • 7

2 Answers2

3

You should use the TZInfo gem.

require 'tzinfo'

tz = TZInfo::Timezone.get('Asia/Kolkata')
utc = DateTime.iso8601('2014-01-03T23:30:00Z')
local = tz.utc_to_local(utc)
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • Is tzinfo compatible with ruby 1.8 and rails 2.3. I tried using this gem but it displayed this error message "no such file to load -- tzinfo" – Dheeraj Tyagi Jul 05 '14 at 08:40
2

If it just a ruby project without rails, also you do not want to install third party gems. Then you have to do it yourself, the following is what I did:

  def convert_time_to_timezone(time, timezone)
    timezone_in_hours = timezone.to_i
    time_in_seconds = time.to_i
    time_in_seconds_in_timezone = time_in_seconds + timezone_in_hours*3600
    utc_time = Time.at(time_in_seconds_in_timezone).utc
    Time.new(utc_time.year, utc_time.month, utc_time.day, utc_time.hour, utc_time.min, utc_time.sec, "#{timezone}:00")
  end

Just provide time (e.g., Time.now) and timezone (e.g., "+11:00", or "-05:00") it will return the time with the specified timezone. example: call convert_time_to_timezone(Time.now, "+11:00") it will return something like

2017-05-31 18:17:13 +1100

If it has rails installed, then you can directly call in_time_zone('"Central Time (US & Canada)"')

Kevin Li
  • 2,068
  • 15
  • 27