LoginSignup
0
0

More than 5 years have passed since last update.

【rails5】当月、前月、翌月の値を取得する方法

Posted at

【rails5】当月、前月、翌月の値を取得する方法

月初と月末の日付を取得したかったので調べました。

コンソールで

 Date.current
 => Mon, 10 Dec 2018 

で今日の日付が取得出来ます。

Date.currentの後に、

今月 Date.current.month
前月 Date.current.prev_month
次月 Date.current.next_month
月初 Date.current.beginning_of_month
月末 Date.current.end_of_month

と付けることでそれぞれの値を取得できる。

now = Date.current

繋げて

前月の月初
now.prev_month.beginning_of_month
=> Thu, 01 Nov 2018 00:00:00 JST +09:00

前月の月初の日にちが取得できました。

今回は月だけを表示させたいので、strftimeでフォーマットを変更します。

前月の月初
now.prev_month.beginning_of_month.strftime("%m")
=> "11"

出来ました。

年も同じです。

今年
 Date.current.year
 => 2018 

ちなみに過去や未来を取得するには、

n年前
Date.current.ago(n.years)

n年後
Date.current.since(n.years)

で取得できます。

3年後
> Date.current.since(3.years)
 => Fri, 10 Dec 2021 00:00:00 JST +09:00

もし1年と7か月前などにする場合はmonthを使って、

1年と7か月前
Date.current.ago(19.month)
 => Wed, 10 May 2017 00:00:00 JST +09:00 

で出来ました。

ちなみにTime.currentだと時間まで取得出来ます。

Time.current
 => Mon, 10 Dec 2018 08:29:13 JST +09:00 
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0