如何在ActiveSupport的TimeZone类中设置时区 [英] How to set timezone in ActiveSupport's TimeZone class

查看:221
本文介绍了如何在ActiveSupport的TimeZone类中设置时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用红宝石慢慢解析文本。但是,在尝试解析字符串时,我仍然遇到错误。



错误: NoMethodError - undefined方法'zone ='用于时间:类:



这是代码:

  require'rubygems'
require'sinatra'
require'chronic'
require'date'
require'time'
require'active_support'
需要'cgi'
require'json'

模块TimeAPI
ZoneOffset = {
'A'=> +1,
'ADT'=> -3,
'AKDT'=> -8,
'AKST'=> -9,
'AST'=> -4,
'B'=> +2,
'BST'=> +1,
'C'=> +3,
'CDT'=> -5,
'CEDT'=> +2,
'CEST'=> +2,
'CET'=> +1,
'CST'=> -6,
'D'=> +4,
'E'=> +5,
'EDT'=> -4,
'EEDT'=> +3,
'EEST'=> +3,
'EET'=> +2,
'EST'=> -5,
'F'=> +6,
'G'=> +7,
'GMT'=> 0,
'H'=> +8,
'HADT'=> -9,
'HAST'=> -10,
'I'=> +9,
'IST'=> +1,
'K'=> +10,
'L'=> +11,
'M'=> +12,
'MDT'=> -6,
'MSD'=> +4,
'MSK'=> +3,
'MST'=> -7,
'N'=> -1,
'O'=> -2,
'P'=> -3,
'PDT'=> -7,
'PST'=> -8,
'Q'=> -4,
'R'=> -5,
'S'=> -6,
'T'=> -7,
'U'=> -8,
'UTC'=> 0,
'V'=> -9,
'W'=> -10,
'WEDT'=> +1,
'WEST'=> +1,
'WET'=> 0,
'X'=> -11,
'Y'=> -12,
'Z'=> 0
}

class App< Sinatra :: Base

set:sessions,false
set:run,false
set:environment,ENV ['RACK_ENV']

def callback
(request.params ['callback'] ||'').gsub(/ [^ a-zA-Z0-9 _] /,'')
end

def prefers_json?
(request.accept.first ||'').downcase =='application / json'
end

def json?
prefers_json? \
|| /\.json$/match((params[:zone] ||'').downcase)\
|| /\.json$/match((params[:time)||'').downcase)
end

def jsonp?
json? &&& callback.present?
end

def格式
format =(request.params.select {| k,v | v.blank?} .first || [nil])。
|| request.params ['format'] \
|| (jsonp??'%B%d,%Y%H:%M:%S GMT%z':'')
CGI.unescape(format).gsub('\\','% ')
end

get'/'do
erb:index
end

get'/favicon.ico'do
$'


get'/:zone /?'do
parse(params [:zone])
end

get'/:zone /:time /?'do
parse(params [:zone],params [:time])
end

def parse(zone = UTC',time ='now')
zone = zone.gsub(/\.json$/,'').upcase
puts zone
offset = ZoneOffset [zone] ||整数(区)
放置偏移
time = time \
.gsub(/\.json$/,'')\
.gsub(/ ^ at / ,'')\
.gsub(/(\d)h /,'\1 hours')\
.gsub(/(\d)min /,'\ 1分钟)\
.gsub(/(\d)m /,'\1分钟')\
.gsub(/(\d)sec /,'\ 1秒')\
.gsub(/(\d)s /,'\1秒')

放置时间

如果prefers_json?
response.headers ['Content-Type'] ='application / json'
end
Time.zone = offset
Chronic.time_class = Time.zone
time = Chronic.parse(time).to_datetime.to_s(format)
time = json? ? {'dateString'=> time} .to_json:time
time = jsonp? ?回调+'('+时间+');':时间
结束
结束
结束

类时间
def to_datetime
#将秒+微秒转换为小数秒数
秒= sec + Rational(usec,10 ** 6)

#将以毫秒为单位测量的UTC偏移量转换为以
#一天的分数。
offset = Rational(utc_offset,60 * 60 * 24)
DateTime.new(年,月,日,小时,最小,秒,偏移量)
end
end

class DateTime
def to_datetime
self
end

def to_s(format ='')
除非format.empty?
strftime(format)
else
strftime
end
end
end

当我尝试设置时区时:

  Time.zone = offset 
Chronic.time_class = Time.zone

它会抛出我的错误。我打印偏移量,根据文档是适当的。我甚至用'Eastern Time(US& Canada)'(直接从 ActiveSupport文档



错误: NoMethodError - undefined方法'now'for UTC:String:



now是需要解析的时间,UTC是时区。 p>

任何和所有的帮助是真正的赞赏。



代码来源: timeapi

解决方案

code> require'active_support / all'?

  irb(main):020: 0>需要'active_support / all'
=> true
irb(main):021:0> Time.zone
=> nil
irb(main):022:0> Time.zone =UTC
=> UTC
irb(main):023:0> Time.zone
=> #< ActiveSupport :: TimeZone:0x007fd859e31910 @ name =UTC,@ utc_offset = nil,@tzinfo =#< TZInfo :: TimezoneProxy:Etc / UTC> @current_period =#< TZInfo :: TimezonePeriod:nil, nil,#< TZInfo :: TimezoneOffset:0,0,UTC>>>>>
irb(main):024:0> Chronic.time_class = Time.zone
=> #< ActiveSupport :: TimeZone:0x007fd859e31910 @ name =UTC,@ utc_offset = nil,@tzinfo =#< TZInfo :: TimezoneProxy:Etc / UTC> @current_period =#< TZInfo :: TimezonePeriod:nil, nil,#< TZInfo :: TimezoneOffset:0,0,UTC>>>>>

看起来像 NoMethodError - undefined method'zone ='for Time:Class :不见了。


I am trying to parse text into a date using chronic in ruby. However, I keep running into an error while trying to parse the string.

Error: NoMethodError - undefined method 'zone=' for Time:Class:

Here is the code:

require 'rubygems'
require 'sinatra'
require 'chronic'
require 'date'
require 'time'
require 'active_support'
require 'cgi'
require 'json'

module TimeAPI
  ZoneOffset = {
    'A' => +1,
    'ADT' => -3,
    'AKDT' => -8,
    'AKST' => -9,
    'AST' => -4,
    'B' => +2,
    'BST' => +1,
    'C' => +3,
    'CDT' => -5,
    'CEDT' => +2,
    'CEST' => +2,
    'CET' => +1,
    'CST' => -6,
    'D' => +4,
    'E' => +5,
    'EDT' => -4,
    'EEDT' => +3,
    'EEST' => +3,
    'EET' => +2,
    'EST' => -5,
    'F' => +6,
    'G' => +7,
    'GMT' => 0,
    'H' => +8,
    'HADT' => -9,
    'HAST' => -10,
    'I' => +9,
    'IST' => +1,
    'K' => +10,
    'L' => +11,
    'M' => +12,
    'MDT' => -6,
    'MSD' => +4,
    'MSK' => +3,
    'MST' => -7,
    'N' => -1,
    'O' => -2,
    'P' => -3,
    'PDT' => -7,
    'PST' => -8,
    'Q' => -4,
    'R' => -5,
    'S' => -6,
    'T' => -7,
    'U' => -8,
    'UTC' => 0,
    'V' => -9,
    'W' => -10,
    'WEDT' => +1,
    'WEST' => +1,
    'WET' => 0,
    'X' => -11,
    'Y' => -12,
    'Z' => 0
  }

  class App < Sinatra::Base

    set :sessions, false
    set :run, false
    set :environment, ENV['RACK_ENV']

    def callback
      (request.params['callback'] || '').gsub(/[^a-zA-Z0-9_]/, '')
    end

    def prefers_json?
      (request.accept.first || '').downcase == 'application/json'
    end

    def json?
      prefers_json? \
        || /\.json$/.match((params[:zone] || '').downcase) \
        || /\.json$/.match((params[:time] || '').downcase)
    end

    def jsonp?
      json? && callback.present?
    end

    def format
      format = (request.params.select { |k,v| v.blank? }.first || [nil]).first \
        || request.params['format'] \
        || (jsonp? ? '%B %d, %Y %H:%M:%S GMT%z' : '')
      CGI.unescape(format).gsub('\\', '%')
    end

    get '/' do
      erb :index
    end

    get '/favicon.ico' do
      ''
    end

    get '/:zone/?' do
      parse(params[:zone])
    end

    get '/:zone/:time/?' do
      parse(params[:zone], params[:time])
    end

    def parse(zone='UTC', time='now')
      zone = zone.gsub(/\.json$/, '').upcase
      puts zone
      offset = ZoneOffset[zone] || Integer(zone)
      puts offset
      time = time \
        .gsub(/\.json$/, '') \
        .gsub(/^at /, '') \
        .gsub(/(\d)h/, '\1 hours') \
        .gsub(/(\d)min/, '\1 minutes') \
        .gsub(/(\d)m/, '\1 minutes') \
        .gsub(/(\d)sec/, '\1 seconds') \
        .gsub(/(\d)s/, '\1 seconds')

      puts time

      if prefers_json?
        response.headers['Content-Type'] = 'application/json'
      end
      Time.zone = offset
      Chronic.time_class = Time.zone
      time = Chronic.parse(time).to_datetime.to_s(format)
      time = json? ? { 'dateString' => time }.to_json : time
      time = jsonp? ? callback + '(' + time + ');' : time
    end
  end
end

class Time
  def to_datetime
    # Convert seconds + microseconds into a fractional number of seconds
    seconds = sec + Rational(usec, 10**6)

    # Convert a UTC offset measured in minutes to one measured in a
    # fraction of a day.
    offset = Rational(utc_offset, 60 * 60 * 24)
    DateTime.new(year, month, day, hour, min, seconds, offset)
  end
end

class DateTime
  def to_datetime
    self
  end

  def to_s(format='')
    unless format.empty?
      strftime(format)
    else
      strftime
    end
  end
end

When I try to set the timezone using:

Time.zone = offset
Chronic.time_class = Time.zone

it throws me that error. I am printing the offset and it is appropriate according to the docs. I even replaced the calculated offset with 'Eastern Time (US & Canada)' (straight from ActiveSupport Docs)

Error: NoMethodError - undefined method 'now' for "UTC":String:

With 'now' being the time that needs to be parsed and "UTC" being the timezone.

Any and all help is truly appreciated.

Code source: timeapi

解决方案

Could you try require 'active_support/all' ?

irb(main):020:0> require 'active_support/all'
=> true
irb(main):021:0> Time.zone
=> nil
irb(main):022:0> Time.zone = "UTC"
=> "UTC"
irb(main):023:0> Time.zone
=> #<ActiveSupport::TimeZone:0x007fd859e31910 @name="UTC", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>, @current_period=#<TZInfo::TimezonePeriod: nil,nil,#<TZInfo::TimezoneOffset: 0,0,UTC>>>>
irb(main):024:0> Chronic.time_class = Time.zone
=> #<ActiveSupport::TimeZone:0x007fd859e31910 @name="UTC", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>, @current_period=#<TZInfo::TimezonePeriod: nil,nil,#<TZInfo::TimezoneOffset: 0,0,UTC>>>>

Look like that NoMethodError - undefined method 'zone=' for Time:Class: is gone.

这篇关于如何在ActiveSupport的TimeZone类中设置时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆