Count number of days between two dates

前端 未结 10 727
暗喜
暗喜 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:38

    to get the number of days in a time range (just a count of all days)

    (start_date..end_date).count
    (start_date..end_date).to_a.size
    #=> 32
    

    to get the number of days between 2 dates

    (start_date...end_date).count
    (start_date...end_date).to_a.size
    #=> 31
    
    0 讨论(0)
  • 2020-12-12 23:43

    None of the previous answers (to this date) gives the correct difference in days between two dates.

    The one that comes closest is by thatdankent. A full answer would convert to_i and then divide:

    (Time.now.to_i - 23.hours.ago.to_i) / 86400
    >> 0
    
    (Time.now.to_i - 25.hours.ago.to_i) / 86400
    >> 1
    
    (Time.now.to_i - 1.day.ago.to_i) / 86400
    >> 1
    

    In the question's specific example, one should not parse to Date if the time passed is relevant. Use Time.parse instead.

    0 讨论(0)
  • 2020-12-12 23:51

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

    0 讨论(0)
  • 2020-12-12 23:51

    I kept getting results in seconds, so this worked for me:

    (Time.now - self.created_at) / 86400
    
    0 讨论(0)
  • 2020-12-12 23:52

    Assuming that end_date and start_date are both of class ActiveSupport::TimeWithZone in Rails, then you can use:

    (end_date.to_date - start_date.to_date).to_i
    
    0 讨论(0)
  • 2020-12-12 23:53
    (end_date - start_date)/1000/60/60/24
    

    any one have best practice please comment below

    0 讨论(0)
提交回复
热议问题