在DateTime到Time转换中的奇怪的Ruby行为 [英] Weird Ruby Behavior in DateTime to Time conversion

查看:168
本文介绍了在DateTime到Time转换中的奇怪的Ruby行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是从DateTime实例获取时间实例



以前在此讨论过,我仍然感到困惑:转换为/从DateTime和Ruby in Ruby


$ b $对于我在irb运行ruby 1.9.3p0(2011-10-30修订版33570)[x86_64-darwin11.2.0],我的工作完美

  1.9.3p0:001>要求'Date'
=> true
1.9.3p0:002>需要'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
=>时间
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七月2012 02:00:00 +0530
1.9.3p0> t2.class
=> DateTime

如何从rails中的DateTime获取Time实例?

解决方案

根据 Rails DateTime.to_time() 的文档


如果自己有0以外的偏移量,将自动返回不变


要更改为0偏移量,请使用 DateTime.utc()

  1.9.3p194:005> t3 = t2.utc 
=>星期六,2012年6月30日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
=>时间


My goal is to get a Time instance from a DateTime instance

This has been previously discussed here and I am still confused : Convert to/from DateTime and Time in Ruby

For me in irb running ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-darwin11.2.0], things work perfectly

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 > 

However when working with rails console v 3.2.3 on same ruby platform

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

What to do to get a Time instance from DateTime in rails?

解决方案

According to the Rails documentation for DateTime.to_time(),

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

To change to a 0 offset, use 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 

这篇关于在DateTime到Time转换中的奇怪的Ruby行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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