trueCamelType trueCamelType - 3 months ago 16
Ruby Question

How can I subtract formatted dates in Ruby, to return a day difference?

This is my first time using Ruby, and I've been given two dates. These two dates are always within 7 days of each other, and I need to get the difference between them.

My issue is, that one of these dates comes from a database, and is formatted like this

YYYY-MM-DD


My other date is just
Time.now
, but I can format it like the other using
Time.now.strftime("%Y-%m-%d")


I don't necessarily think I need to format the second date, but I was hoping if I got them both in the same format, I could just subtract them....which does not appear to be the case.

Any ideas how I could have this just return an integer for how many days are between the two dates, if one date is a pre-formatted date from a db?

Answer

(date1.to_date - date2.to_date).to_i should give you the difference in days.