如何从下面的代码中获取整数形式的月份
3.2.21@2.1.3 (#<VouchersController:0x007ff453)> t = (Date.today + 5).to_s
=> "2015-12-01"
3.2.21@2.1.3 (#<VouchersController:0x007ff453)> t.to_i
=> 2015
3.2.21@2.1.3 (#<VouchersController:0x007ff453)>
我可以得到年份。但是我如何将月份作为整数返回 12
?
最佳答案
您获得年份的原因只是您将字符串 "2015-12-01"
转换为整数。
当您在 Ruby 字符串上使用 to_i
时,它仅使用前导数字字符,然后丢弃字符串的其余部分。当它到达第一个 -
字符时,它会停止解析为整数并返回目前为止的内容:2015
。
为了使用Date
的实际功能,不要使用to_s
将对象转换成字符串。
require 'date'
t = Date.today + 5 # => #<Date: 2015-11-30 ((2457357j,0s,0n),+0s,2299161j)>
t.year # => 2015
t.month # => 11
关于ruby - 从 Date.today 获取月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33931662/