web-dev-qa-db-ja.com

Ruby

Ruby)で現在の日付と月を特定の形式で取得するにはどうすればよいですか?

今日が2012年6月8日の場合、201206

また、201212では、次の月は201301になることを考慮して、現在の月から次の月を取得できるようにしたいと考えています。

18
Hommer Smith

私はこのようにします:

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)>
33
Michael Kohl

今月:

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
15
Josh

Ruby 2の時点では、 "next_month"は日付のメソッドです:

require "Date"

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

Date.today.next_month.strftime("%Y%m")
# => "201408"
7
Amin Ariana
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
3
Mahattam

そのようなものには http://strfti.me/ を使用してください

strftime "%Y%m"
1
three

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"
0
Wasim