LoginSignup
321
303

Railsでの日付操作でよく使うものまとめ

Last updated at Posted at 2016-01-03

対象バージョン

  • ruby 2.1.2
  • Rails 4.2.1

以下で利用しているTimeクラスは、ActiveSupportの拡張したTimeクラスを利用しています。

現在日時の取得

now = Time.current 

N日前・N日後

now = Time.current 

# 昨日
now.yesterday

# 翌日
now.tomorrow

# N日前,N日後
now.ago(3.days)
now.since(3.days)

Nヶ月前・Nヶ月後

now = Time.current 

# 前月
now.prev_month

# 翌月
now.next_month

# Nヶ月前,Nヶ月後
now.ago(3.month)
now.since(3.month)

N年前・N年後

now = Time.current 

# 前年
now.prev_year

# 翌年
now.next_year

# N年前,N年後
now.ago(3.years)
now.since(3.years)

その他

now = Time.current 

# 月初
now.beginning_of_month

# 月末
now.end_of_month

# 今週の最初
now.beginning_of_week

# 今週の末
now.end_of_week

# 先週の月曜日
now.prev_week(:monday)

# 翌週の月曜日
now.next_week(:monday)

321
303
6

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
321
303