简体   繁体   中英

Get the difference in days between two dates Rails “Date”

What is the proper way to subtract or add dates in Rails?

I tried the intuitive way but got Rational:

irb(main):089:0> Date.today.increase_by("3 days")

=> Sun, 19 May 2019

irb(main):090:0> Date.today

=> Thu, 16 May 2019

irb(main):091:0> Date.today.increase_by("3 days") - Date.today

=> (3/1)

Disclaimer: Please note that I am new to Ruby and Rails as well. 2 months of experience so far :)

You can use

Date.today # Thu, 16 May 2019

Date.today + 3 # Thu, 19 May 2019

Date.today - 3 # Thu, 13 May 2019

For Difference

Date.today + 3 # Thu, 19 May 2019

Date.today - 3 # Thu, 13 May 2019

(d1 - d2).to_i # 6 (Days)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM