gpt4 book ai didi

ruby-on-rails - 日期时间到时间转换中奇怪的 Ruby 行为

转载 作者:数据小太阳 更新时间:2023-10-29 07:30:42 26 4
gpt4 key购买 nike

我的目标是从 DateTime 实例获取 Time 实例

这之前已经在这里讨论过,但我仍然很困惑:Convert to/from DateTime and Time in Ruby

对我来说,在运行 ruby​​ 1.9.3p0(2011-10-30 修订版 33570)[x86_64-darwin11.2.0] 的 irb 中,一切正常

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 获取时间实例?

最佳答案

根据Rails documentation for DateTime.to_time() ,

If self has an offset other than 0, self will just be returned unaltered

要更改为 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

关于ruby-on-rails - 日期时间到时间转换中奇怪的 Ruby 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11277454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com