Count number of days between two dates

前端 未结 10 728
暗喜
暗喜 2020-12-12 23:26

How do I count the number of days between these two dates?

start_date = Date.parse \"2012-03-02 14:46:21 +0100\"
end_date =  Date.parse \"2012-04-02 14:46:21         


        
相关标签:
10条回答
  • 2020-12-12 23:54

    To have the number of whole days between two dates (DateTime objects):

    ((end_at - start_at).to_f / 1.day).floor
    
    0 讨论(0)
  • 2020-12-12 23:56
    def business_days_between(date1, date2)
      business_days = 0
      date = date2
      while date > date1
       business_days = business_days + 1 unless date.saturday? or date.sunday?
       date = date - 1.day
      end
      business_days
    end
    
    0 讨论(0)
  • 2020-12-12 23:58

    Rails has some built in helpers that might solve this for you. One thing to keep in mind is that this is part of the Actionview Helpers, so they wont be available directly from the console.

    Try this

    <% start_time =  "2012-03-02 14:46:21 +0100" %>
    <% end_time   =  "2012-04-02 14:46:21 +0200" %>
    <%= distance_of_time_in_words(start_time, end_time)  %>
    
     "about 1 month"
    
    0 讨论(0)
  • 2020-12-13 00:01

    To get the number of days difference by two dates:

    (start.to_date...end.to_date).count - 1
    or 
    (end.to_date - start.to_date).to_i
    
    0 讨论(0)
提交回复
热议问题