Get current month with Sequel

元气小坏坏 提交于 2020-01-06 12:38:12

问题


i would like recover a list of entries for the current month with Sequel, i try:

Entry.where(:date >= Date.month).sum(:duration)

or

Entry.where(:date.like('%/06/2013')).sum(:duration)

and other ...

But none of them seemed to work

Thanks in advance


回答1:


If you want all entries the current month and the current year, it's probably easiest to use a range:

d = Date.today
Entry.where(:date=> Date.new(d.year, d.month)...(Date.new(d.year, d.month) >> 1)).sum(:duration)

If you want the current month in any year, Sequel has built in support for this:

Entry.where(Sequel.extract(:month, :date) => Date.today.month).sum(:duration)



回答2:


You'll need to think in terms of how a database thinks, and how Sequel turns Ruby ranges into SQL:

require 'date'

today = Date.today                          # => #<Date: 2013-07-03 ((2456477j,0s,0n),+0s,2299161j)>
first_of_month = (today - today.day) + 1
first_of_month                              # => #<Date: 2013-07-01 ((2456475j,0s,0n),+0s,2299161j)>
next_month = today + 31                     # => #<Date: 2013-08-03 ((2456508j,0s,0n),+0s,2299161j)>
last_of_month = next_month - next_month.day # => #<Date: 2013-07-31 ((2456505j,0s,0n),+0s,2299161j)>
last_of_month                               # => #<Date: 2013-07-31 ((2456505j,0s,0n),+0s,2299161j)>

Entry.where(:date => [first_of_month .. last_of_month]).sum(:duration)

I'd show you the SQL output, but I don't know the database type you're using, and, well, I'm lazy.

Often, you can play tricks inside the DB by truncating "now" to remove the day, then finding all timestamps whose truncated date matches it. That's a lot more specific to the DBM than using Sequel, which already knows how to deal with ranges when converting them to a "between"-type statement.



来源:https://stackoverflow.com/questions/17187609/get-current-month-with-sequel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!