Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting two dates in ruby on rails

I'm subtracting two dates in my model in this way:-

  def total_days
      self.to_date - self.from_date
  end

My date is in Mysql Date (YYYY-MM-DD)format.

When displaying my date in view it is giving me 5/1 days. Even though 5 is correct it is appending '/1' to the days. How can i remove this. Is there any better way of doing it?

like image 949
Sachin Prasad Avatar asked Nov 03 '12 10:11

Sachin Prasad


People also ask

How do I get the difference between two dates in rails?

With the Date (and DateTime) classes you can do (end_date - start_date). to_i to get the number of days difference.

How do you subtract a date object in Java?

The class also provides a method minusDays() that is used to subtract number of days from the current date. The syntax of the minusDays() method is as follows: public LocalDate minusDays (long daysToSubtract)

Can we subtract date in Java?

The minusDays() method of LocalDate class in Java is used to subtract the number of specified day from this LocalDate and return a copy of LocalDate. For example, 2019-01-01 minus one day would result in 2018-12-31.


2 Answers

try this, for example

require 'date'
$ now = Date.today
$ before = Date.today + 2.days
$ difference_in_days = (before - now).to_i

for your solution

def total_days
  difference_in_days = (self.to_date - self.from_date).to_i
end
like image 109
Dipak Panchal Avatar answered Sep 21 '22 00:09

Dipak Panchal


You can also work in the view with:

<%= distance_of_time_in_words(contract['start_date'], contract['end_date'])%>
like image 39
Wouter Schoofs Avatar answered Sep 19 '22 00:09

Wouter Schoofs