ssnegi
ssnegi

Reputation: 183

Finding days between 2 days in Ruby on Rails

I am facing some problem in finding the days between 2 dates.

The scenario is as follow :

time = Time.new
enddate_timestamp = time.strftime("%Y-%m-%d %H:%M:%S")               
startdate = @logInfo.updated_at   #here updated_at is the column in the db .

What is the best way to find the days ?

Upvotes: 1

Views: 587

Answers (4)

Simone Carletti
Simone Carletti

Reputation: 176412

There are several possible solutions. A possibility is to create a Range with the dates, then convert the range into an array

# set the boundaries
today = Time.current
past  = 5.days.ago

Note that both boundaries are time instances. We should cast them into dates. I used time(s) because your column is a time.

range = past.to_date..today.to_date 
# => Sun, 29 Dec 2013..Fri, 03 Jan 2014 

Use to_a to expand the range getting all the days

range.to_a
# => [Sun, 29 Dec 2013, Mon, 30 Dec 2013, Tue, 31 Dec 2013, Wed, 01 Jan 2014, Thu, 02 Jan 2014, Fri, 03 Jan 2014]

range.count
# => 6

You can also enumerate them

range.each { |day| puts day.day }
29
30
31
1
2
3

Upvotes: 1

Manish
Manish

Reputation: 111

(startdate.beginning_of_day..enddate_timestamp.to_time.beginning_of_day).step(1.day) do |day|    
  puts day
end

P.S: Performance wise it's not good.

Upvotes: 0

astropanic
astropanic

Reputation: 10939

now    = Time.now
future = Time.now + 100 days

while now < future
  now = now + 1.day
  puts now
end

This will give you the dates, not the days count.

Upvotes: 0

nikolayp
nikolayp

Reputation: 17929

Post.where(["date(created_at) BETWEEN ? AND ?", Date.yesterday, Date.tomorrow]

More details: http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-where

Upvotes: 1

Related Questions