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?
With the Date (and DateTime) classes you can do (end_date - start_date). to_i to get the number of days difference.
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)
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.
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
You can also work in the view with:
<%= distance_of_time_in_words(contract['start_date'], contract['end_date'])%>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With