我的目标是从DateTime实例获取Time实例
此处已在此处讨论,我仍然感到困惑:Convert to/from DateTime and Time in Ruby
对于我来说,运行ruby 1.9.3p0(2011-10-30修订版33570)[x86_64-darwin11.2.0],事情很顺利
1.9.3p0 :001 > require 'Date'
=> true
1.9.3p0 :002 > require 'Time'
=> true
1.9.3p0 :003 > t=DateTime.now
=> #<DateTime: 2012-07-01T01:57:32+05:30 ((2456109j,73652s,621060000n),+19800s,2299161j)>
1.9.3p0 :004 > t2=t.to_time
=> 2012-07-01 01:57:32 +0530
1.9.3p0 :005 > t.class
=> DateTime
1.9.3p0 :006 > t2.class
=> Time
1.9.3p0 :007 >
但是在同一个ruby平台上使用rails console v 3.2.3时
1.9.3p0 :001 > t=DateTime.now
=> Sun, 01 Jul 2012 02:00:00 +0530
1.9.3p0 :002 > t.class
=> DateTime
1.9.3p0 :003 > t2=t.to_time
=> Sun, 01 Jul 2012 02:00:00 +0530
1.9.3p0 > t2.class
=> DateTime
如何从rails中的DateTime获取Time实例?
答案 0 :(得分:5)
根据Rails documentation for DateTime.to_time()
,
如果self的偏移量不是0,那么self将只返回不变的
要更改为0偏移,请使用DateTime.utc()
。
1.9.3p194 :005 > t3=t2.utc
=> Sat, 30 Jun 2012 20:43:21 +0000
1.9.3p194 :006 > t3.offset
=> (0/1)
1.9.3p194 :007 > t4=t3.to_time
=> 2012-06-30 20:43:21 UTC
1.9.3p194 :008 > t4.class
=> Time