95
85

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.

日付の年や月の範囲で検索したい場合

Last updated at Posted at 2016-01-31

ある年の年始から年末まで、月初から月末までで範囲検索したくなることがあると思うけど、
ActiveSupportのメソッドを利用すれば下記のように漏れなくスマートに書くことができる。

コード例

# 仮の日付
search_date = '2016-1-25'

# 年での指定
Item.where(created_at: search_date.in_time_zone.all_year)

# 月での指定
Item.where(created_at: search_date.in_time_zone.all_month)

# 日での指定
Item.where(created_at: search_date.in_time_zone.all_day)

発行されるSQLクエリ

-- 年での指定
SELECT "items".* 
FROM "items"  
WHERE ("items"."created_at" BETWEEN '2016-01-01 00:00:00' AND '2016-12-31 23:59:59')

-- 月での指定
SELECT "items".* 
FROM "items"  
WHERE ("items"."created_at" BETWEEN '2016-01-01 00:00:00' AND '2016-01-31 23:59:59')

-- 日での指定
SELECT "items".* 
FROM "items"  
WHERE ("items"."created_at" BETWEEN '2016-01-25 00:00:00' AND '2016-01-25 23:59:59')

例では日付の文字列をTimeクラスに変換しているけどもちろんTime.current.all_yearなどと書いて使うこともできる。

参考

95
85
2

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
95
85

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?