0

我有一个具有日期时间值的 XML 文件。我遍历元素并获取属性值timeutc

我设法将其转换为本地时区,但我想做的是将其转换为任何时区、PST、CST、EST。

$Appointments = '<appointments><appointment timeutc="2013-10-10T06:00:00" /><appointment timeutc="2013-10-10T06:00:00" /><appointment timeutc="2013-10-10T15:00:00" /></appointments>'
index = 0

doc = REXML::Document.new("#{$Appointments}")

doc.elements.each("appointments/appointment") do |element|
  index += 1
  value = element.attribute("timeutc").value

  to_datetime = DateTime.parse(value).to_s
  to_UTC = Time.iso8601(to_datetime).to_s

  local_time = Time.iso8601(to_datetime).localtime

  puts local_time # => 2013-10-09 23:00:00 -0700 

  puts   local_time.strftime("%A") # => Wednesday
  puts   local_time.strftime("%B") # => October
  puts   local_time.strftime("%-d") # => 9
  puts   local_time.strftime("%l") # => 11
  puts   local_time.strftime("%M") # => 00
  puts   local_time.strftime("%p") # => PM

end
4

2 回答 2

1

您可以使用in_time_zone方法:

对于 CST:

local_time.in_time_zone('Central Time (US & Canada)')

对于太平洋标准时间:

local_time.in_time_zone('Pacific Time (US & Canada)')

森林:

local_time.in_time_zone('Eastern Time (US & Canada)')
于 2013-10-11T21:07:15.897 回答
0

Ruby 对时区的支持不是那么好(不确定这是否随着 2.0 改变),因此有各种 ActiveSupport 库。

Ruby 查看环境变量TZ来确定要在哪个区域中操作:

irb [1.9.3]$ ENV["TZ"]  # Ruby will look elsewhere and see that I'm in NYC
=> nil
irb [1.9.3]$ Time.iso8601 "2013-10-10T06:00:00"
=> 2013-10-10 06:00:00 -0400
irb [1.9.3]$ ENV["TZ"]="America/Los_Angeles"
=> "America/Los_Angeles"
irb [1.9.3]$ Time.now.zone
=> "PDT"
irb [1.9.3]$ Time.iso8601 "2013-10-10T06:00:00"
=> 2013-10-10 06:00:00 -0700

所以......虽然我强烈鼓励使用主动支持方法,但您可以使用这样的方法:

irb [1.9.3]$ def parse_in_zone(date, zone)
1{             old = ENV["TZ"]
1{             ENV["TZ"] = zone
1{             Time.iso8601 date
1{           ensure
1*             ENV["TZ"] = old
1{           end
=> nil
irb [1.9.3]$ parse_in_zone "2013-10-10T06:00:00", "America/Los_Angeles"
=> 2013-10-10 06:00:00 -0700
irb [1.9.3]$ parse_in_zone "2013-10-10T06:00:00", "America/New_York"
=> 2013-10-10 06:00:00 -0400

另请注意,这DateTime.parse(value)不是必需的。它在解析日期时考虑字符串的区域:

irb [1.9.3]$ DateTime.parse("2013-10-10T06:00:00").zone
=> "+00:00"
irb [1.9.3]$ DateTime.parse("2013-10-10T06:00+04:00").zone
=> "+04:00"
irb [1.9.3]$ DateTime.parse("2013-10-10T06:00+07:00").zone
=> "+07:00"

请注意,在您的情况下,我认为 string:2013-10-10T06:00:00不是有效的 iso 日期/时间(额外:00),但看起来 ruby​​ 不在乎:

irb [1.9.3]$ DateTime.parse("2013-10-10T06:00:0000:000000").to_s
=> "2013-10-10T06:00:00+00:00"
于 2013-10-12T00:15:23.220 回答