需要将格式2017-03-30 21:25:09的UTC日期时间更改为其他时区。红宝石

时间:2017-03-20 17:13:34

标签: ruby time timezone

我有以下UTC格式的字符串:"2017-03-30 21:25:09"。我需要将其转换为"America/Los_Angeles" and "America/New_York"时区。

我尝试了以下但是它没有用。

utc_time = Time.parse(to_datetime.to_s).utc
pacific_time = utc_time + Time.zone_offset("PDT")

我也尝试使用DateTime#strptime,但这也不起作用。

to_datetime = DateTime.strptime(my_time_string, "%y-%m-%d %H:%M:%S")

如何更改字符串以使其引用不同的时区?

3 个答案:

答案 0 :(得分:1)

ActiveSupport提供in_time_zone帮助程序方法。例如,您可以手动设置TimeZone,而不是使用操作系统的时区。

Time.zone = 'Hawaii'             # => 'Hawaii'
DateTime.new(2000).in_time_zone  # => Fri, 31 Dec 1999 14:00:00 HST -10:00

您还可以传入TimeZone实例或字符串,将TimeZone标识为参数,转换将基于该区域而不是Time.zone

DateTime.new(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00

更多信息位于" ActiveSupport::TimeWithZone"。

答案 1 :(得分:1)

使用TZInfo gem

require 'tzinfo'

# parse the UTC time
utcTime = Time.parse("2017-03-30 21:25:09 UTC")
puts utcTime # "2017-03-30 21:25:09 UTC"

# convert it to a time zone
tz = TZInfo::Timezone.get('America/New_York')
localTime = tz.utc_to_local(utcTime)
# you cannot just puts this localTime, because the abbrevation will be incorrect

# you can get format directly from here and get the correct abbreviation with %Z
localString = tz.strftime("%Y-%m-%d %H:%M:%S %Z", utc = utcTime)
puts localString # "2017-03-30 17:25:09 EDT"

# as of v1.2.3, you can get the offset correctly with %z
localString = tz.strftime("%Y-%m-%d %H:%M:%S %z", utc = utcTime)
puts localString # "2017-03-30 17:25:09 -04:00"

# for older versions of tzinfo, %z didn't work so you had to create the offset manually
offset = tz.period_for_utc(utcTime).utc_total_offset
hoursOffset = (offset / 3600.0).truncate
minutesOffset = (offset.abs / 60) % 60
offsetString = sprintf("%+03d:%02d", hoursOffset, minutesOffset)
puts offsetString # "-04:00"

答案 2 :(得分:0)

这是我解决它的方式,感谢https://stackoverflow.com/users/634824/matt-johnson

Input =>  convert_date_from_utc('2017-03-20 22:29:26', 'America/New_York')
Output=>  2017-03-20T18:29:26-04:00

  # convert utc date to other time_zone with offset
  def convert_date_from_utc(date, time_zone)
    utcTime = Time.parse(date)
    tz = TZInfo::Timezone.get(time_zone)
    local_time = tz.utc_to_local(utcTime).to_s[0..18].gsub!(' ','T')
    offset = tz.period_for_utc(utcTime).utc_total_offset
    hoursOffset = (offset / 3600.0).truncate
    minutesOffset = (offset.abs / 60) % 60
    offsetString = sprintf("%+03d:%02d", hoursOffset, minutesOffset)
    local_time+offsetString
  end