Ruby ActiveSupport::TimeWithZone#to#date返回错误的日期
我需要来自Ruby ActiveSupport::TimeWithZone#to#date返回错误的日期,ruby,ruby-on-rails-3,datetime,Ruby,Ruby On Rails 3,Datetime,我需要来自ActiveSupport::TimeWithZone实例的日期部分。我为此使用了to_date函数,但它会提前一天返回日期 例如,如果datetime是2012-04-11 09:05:00 UTC,如果我调用来指定日期,则返回2012-04-10,但2012-04-11 此外,我没有使用特定时区(默认为UTC) 该应用程序运行在Ruby 1.8.7和Rails 3.0.2 有人能告诉我为什么日期不对吗?另外,请告诉我是否有更好的方法从给定的DateTime(实例ActiveSupp
ActiveSupport::TimeWithZone
实例的日期部分。我为此使用了to_date
函数,但它会提前一天返回日期
例如,如果datetime是2012-04-11 09:05:00 UTC
,如果我调用来指定日期
,则返回2012-04-10
,但2012-04-11
此外,我没有使用特定时区(默认为UTC)
该应用程序运行在Ruby 1.8.7
和Rails 3.0.2
有人能告诉我为什么日期不对吗?另外,请告诉我是否有更好的方法从给定的DateTime
(实例ActiveSupport::TimeWithZone
)获取日期(实例date
)部分
编辑:
这里也有人面临同样的问题
注意:时区
返回'UTC'
谢谢。我在这里分享你的发现和解决方案
可能有一些gem覆盖了迄今为止的实现,可能实现不正确,并且可能会调用此被覆盖的版本
在我的案例中,罪魁祸首是ruby单元
gem
根本原因:ruby单位
gem包含在应用程序的gem文件中
问题分析:
Gemfile
# Ruby-units overrides String class #to method, hence placed before Rails
gem "ruby-units" # Loads first and then rails is loaded
gem "rails", "3.0.11"
..
..
..
..
unless Time.instance_methods.include?(:to_date)
# :nocov_19:
# @return [Date]
def to_date
x=(Date.civil(1970,1,1)+((self.to_f+self.gmt_offset)/86400.0)-0.5)
Date.civil(x.year, x.month, x.day)
end
# :nocov_19:
end
..
..
time.rb文件(ruby单位gem代码库)
假设UTC
时区中的当前时间为
Wed,2012年4月11日10:12:17 UTC+00:00
表示为ActiveSupport::TimeWithZone
例如。
当我们执行时,从rails应用程序返回
日期2012-04-10
不正确
上述错误行为的罪魁祸首是迄今为止实施的方法
由ruby单元提供
gem
下面是演示上述错误行为的示例程序。to\u date
方法与由ruby units
gem实现的方法相同,只是在方法中添加了一个参数,即date\u time
,并且实现中的self
被参数替换
“日期和时间”
确认上述发现的Ruby程序示例:
require 'rubygems'
require 'active_support/all'
class TestDT
def to_date(date_time)
#x=(Date.civil(1970,1,1)+((self.to_f+self.gmt_offset)/86400.0)-0.5)
x=(Date.civil(1970,1,1)+((date_time.to_f+date_time.gmt_offset)/86400.0)-0.5)
Date.civil(x.year, x.month, x.day)
end
end
tdt = TestDT.new
utc_time = Time.now.in_time_zone('UTC')
puts tdt.to_date(utc_time)
输出(撰写本文时的日期为周三,2012年4月11日08:35:12 UTC+00:00
):
解决方案:
从gem文件中删除ruby单元
gem,或者在rails gem之后加载它
解决方法:不要执行datetime.to\u date
,而是使用datetime.to\u.to\u date
Time.zone的值是多少?@FrederickCheung Time.zone return utc您调用的ActiveSupport::TimeWithZone
对象的zone
的输出是什么?@shime它返回
$ ruby test_date_time.rb
2012-04-10