以Ruby格式YYYYMM格式获取当前年份和月份(以及下个月)

时间:2012-06-08 21:28:03

标签: ruby date time

如何以特定格式获取Ruby中的当前日期和月份?

如果今天是2012年6月8日,我想获得201206

此外,我希望能够从下一个月开始,考虑到 201212 ,下个月 201301

6 个答案:

答案 0 :(得分:33)

我会这样做:

require 'date'
Date.today.strftime("%Y%m")
#=> "201206"
(Date.today>>1).strftime("%Y%m")
#=> "201207"

Date#>>的优势在于它会自动为您处理某些事情:

Date.new(2012,12,12)>>1
#=> #<Date: 2013-01-12 ((2456305j,0s,0n),+0s,2299161j)>

答案 1 :(得分:15)

当月:

date = Time.now.strftime("%Y%m")

下个月:

if Time.now.month == 12
  date = Time.now.year.next.to_s + "01"
else
  date = Time.now.strftime("%Y%m").to_i + 1
end

答案 2 :(得分:7)

从Ruby 2开始,“next_month”是Date上的方法:

require "Date"

Date.today.strftime("%Y%m")
# => "201407"

Date.today.next_month.strftime("%Y%m")
# => "201408"

答案 3 :(得分:3)

require 'date'
d=Date.today                    #current date
d.strftime("%Y%m")              #current date in format
d.next_month.strftime("%Y%m")   #next month in format

答案 4 :(得分:1)

使用http://strfti.me/来表达那种东西

strftime "%Y%m"

答案 5 :(得分:0)

Ruby 2 Plus和rails 4 plus。

通过使用以下功能,您可以找到所需的结果。

Time.now #current time according to server timezone
Date.today.strftime("%Y%m") # => "201803"

Date.today.next_month.strftime("%Y%m") # => "201804"
相关问题