Convert time to other timezone

我怕爱的太早我们不能终老 提交于 2019-11-28 12:42:35

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)

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)"')

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!