LoginSignup
44
39

RailsのDate型のサンプル

Last updated at Posted at 2018-03-23

株式会社TECH LUCKという会社で代表兼エンジニアをしている齊藤です。

Ruby on Railsで、Date型を使う機会があったので、サンプルコードとして使い方をまとめてみました。
実行結果はサンプルコードの下に記述してあります。
すべて 2018/01/05 に実行した結果ととなっています。

基本的な使い方

年、月、日を指定して取得する

Date.new(2017, 01, 01)
# => Sun, 01 Jan 2017

今日の年月日を取得する

Date.today
# Fri, 05 Jan 2018

今日の日付を取得する

Date.today.day
# 5

今月の月を取得する

Date.today.month
# 1

今年の年を取得する

Date.today.month
# 2018

昨日の日付を取得する

Date.yesterday
# Thu, 04 Jan 2018

〇〇日前、〇〇日後

~~~s_ago, ~~~s_since というメソッドが有効です。

おとといの日付を取得する

Date.today.days_ago(2)
# Wed, 03 Jan 2018

翌日の日付を取得する

Date.tomorrow
# Sat, 06 Jan 2018

2日後の日付を取得する

Date.today.days_since(2)
# Sun, 07 Jan 2018

先月の日付を取得する

Date.today.last_month  #Date.last_monthだとエラーが起きる
# Tue, 05 Dec 2017

翌月の日付を取得する

Date.today.next_month  #Date.next_monthだとエラーが起きる
# Mon, 05 Feb 2018

昨年の日付を取得する

Date.today.last_year
# Thu, 05 Jan 2017

翌年の日付を取得する

Date.today.next_year
# Sat, 05 Jan 2019

始めの日付、終わりの日付

beginning_of_~~~, end_of_~~~ というメソッドが有効です。

今週の始めの日の日付を取得する

Date.today.beginning_of_week
# Mon, 01 Jan 2018

今週の終わりの日の日付を取得する

Date.today.end_of_week
# Sun, 07 Jan 2018

今月の始めの日の日付を取得する

Date.today.beginning_of_month
# Mon, 01 Jan 2018

先月・翌月の始めの日の日付を取得する

#先月
Date.today.last_month.beginning_of_month
# Fri, 01 Dec 2017

#翌月
Date.today.next_month.beginning_of_month
# Thu, 01 Feb 2018

今月の終わりの日の日付を取得する

Date.today.end_of_month
# Wed, 31 Jan 2018

先月・翌月の終わりの日の日付を取得する

#先月
Date.today.last_month.end_of_month
# Wed, 31 Jan 2018

#翌月
Date.today.next_month.end_of_month
# Wed, 28 Feb 2018
44
39
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
44
39