We often stuck, how to manipulate Date in our rails Application.
We have two Date objects in Ruby
Time.now() // This will give Today's date
#=> 2016-05-17 17:02:28 +0530
Date.new() // This will need some arguments to pass.
#=> Mon, 01 Jan -4712 //Otherwise this will give result like this
Time.now() always return the Today's date with the Time Zone, you are working in.
While Date.new() is the new object of Date. we can create an object by passing arguments.
for example
Date.new(1991)
=> Tue, 01 Jan 1991
Date.new(1991,3)
=> Fri, 01 Mar 1991
Date.new(1991,3,17)
=> Sun, 17 Mar 1991
Now, Lets talk about Date in Active Record.
We can Fetch results by the created_by of any record. Then
#Data for current week
Article.where(created_by:(Date.today.beginning_of_week..Date.today.end_of_week))
# => Article Load (0.6ms) SELECT "articles".* FROM "articles" WHERE ("articles"."created_by" BETWEEN '2016-05-16' AND '2016-05-22')
#Data for current month
Article.where(created_by: (Date.today.beginning_of_month..Date.today.end_of_month))
# => Article Load (0.6ms) SELECT "articles".* FROM "articles" WHERE ("articles"."created_by" BETWEEN '2016-05-01' AND '2016-05-31')
#Data for current year
Article.where(created_by: (Date.today.beginning_of_year..Date.today.end_of_year))
# => Article Load (0.7ms) SELECT "articles".* FROM "articles" WHERE ("articles"."created_by" BETWEEN '2016-01-01' AND '2016-12-31')
#Data for current weekdays
Article.where(created_by: (Date.today.beginning_of_week..Date.today.end_of_week-2))
# => Article Load (0.6ms) SELECT "articles".* FROM "articles" WHERE ("articles"."created_by" BETWEEN '2016-05-16' AND '2016-05-20')
#Data for current weekends
Article.where(created_by: (Date.today.end_of_week-1..Date.today.end_of_week))
# => Article Load (0.6ms) SELECT "articles".* FROM "articles" WHERE ("articles"."created_by" BETWEEN '2016-05-21' AND '2016-05-22')
#Data for particular weekends
new_date = Date.new(1991,8,15)
=> Thu, 15 Aug 1991
Article.where(created_by: (new_date.end_of_week-1..new_date.end_of_week))
#=> Article Load (0.6ms) SELECT "articles".* FROM "articles" WHERE ("articles"."created_by" BETWEEN '1991-08-17' AND '1991-08-18')
There are many more methods but these are some which we must care about
0 Comment(s)