3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[ActiveSupport]日付の範囲指定で便利なメソッド

Last updated at Posted at 2018-02-22

###はじめに
ActiveSupportで便利だなと思った書き方の自分用メモです。
1年、1月、1日単位でループさせたい場合に簡潔に記載できます。

####コード

# 現在の日付
today = DateTime.current
# => Thu, 22 Feb 2018 22:06:56 +0900

# 1年 (1月1日 ~ 12月31日)
today.all_year.each { |d| }
# => Mon, 01 Jan 2018 00:00:00 +0900..Mon, 31 Dec 2018 23:59:59 +0900

# 1ヶ月 (2月1日 ~ 2月28日までが範囲となる)
today.all_month.each { |d| }
#=> Thu, 01 Feb 2018 00:00:00 +0900..Wed, 28 Feb 2018 23:59:59 +0900

# 1日 (2月22日 00:00:00 ~ 23:59:59が範囲となる)
today.all_day.each { |d| }
# => Thu, 22 Feb 2018 00:00:00 +0900..Thu, 22 Feb 2018 23:59:59 +0900

####おまけ
ActiveSupportの実装の抜粋を記載します。
beginning_of_XX,end_of_XXを使用してさらに直感的で便利になるように考えられているのだと思います。
もしall系のメソッドをしらなければ、自分で同じこと実装しそうですので、
beginning_of_xxでActiveSupportのソースを検索して確認するのも重要なことですね。
Rangeの範囲指定をeachしていることもわかりますね。

active_support/core_ext/date_and_time/calculations.rb
# Returns a Range representing the whole year of the current date/time.
def all_year
  beginning_of_year..end_of_year
end

# Returns a Range representing the whole month of the current date/time.
def all_month
  beginning_of_month..end_of_month
end

# Returns a Range representing the whole day of the current date/time.
def all_day
  beginning_of_day..end_of_day
end
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?