How to calculate how many years passed since a given date in Ruby?

前端 未结 13 2198
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 16:33

This question was here for other languages, so let here be one for Ruby.

How do I calculate number of complete years that have passed from a given date? As you prob

相关标签:
13条回答
  • 2020-12-09 16:46

    How about something like:

    def years_diff(from_time,to_time)
      (((to_time - from_time).abs)/ (365 * 24 * 60 * 60)).to_i
    end
    
    years_diff(Time.now,Time.local(1950,03,22)) #=> 59
    years_diff(Time.now,Time.local(2009,03,22)) #=> 0
    years_diff(Time.now,Time.local(2008,03,22)) #=> 1
    
    0 讨论(0)
  • 2020-12-09 16:51

    d2.year - d1.year - (d2.month > d1.month || (d2.month == d1.month && d2.day >= d1.day) ? 0 : 1)

    0 讨论(0)
  • 2020-12-09 16:52

    How about this:

    def age_in_years(date)
      # Difference in years, less one if you have not had a birthday this year.
      today = Date.today
      age = today.year - date.year
      age = age - 1 if [date.day, date.month, today.year].join('/').to_date > Date.today
    end
    
    0 讨论(0)
  • 2020-12-09 16:53

    you can use the ruby gem adroit-age

    It works for leap years also..

    age = AdroitAge.find_age("23/01/1990")
    

    Update

    require 'adroit-age'
    
    dob =  Date.new(1990,1,23)
    or
    dob = "23/01/1990".to_date
    
    age = dob.find_age
    #=> 23
    
    0 讨论(0)
  • 2020-12-09 16:56

    An approach that handles leap years

    Whenever you're calculating elapsed years since a date, you have to decide how to handle leap year. Here is my approach, which I think is very readable, and is able to take leap years in stride without using any "special case" logic.

    def years_completed_since(start_date, end_date)
    
      if end_date < start_date
        raise ArgumentError.new(
          "End date supplied (#{end_date}) is before start date (#{start_date})"
        )
      end
    
      years_completed = end_date.year - start_date.year
    
      unless reached_anniversary_in_year_of(start_date, end_date)
        years_completed -= 1
      end
    
      years_completed
    end
    
    # No special logic required for leap day; its anniversary in a non-leap
    # year is considered to have been reached on March 1.
    def reached_anniversary_in_year_of(original_date, new_date)
      if new_date.month == original_date.month
        new_date.day >= original_date.day
      else
        new_date.month > original_date.month
      end
    end
    
    0 讨论(0)
  • 2020-12-09 16:56

    withing http://github.com/radar/dotiw

    Jack is <%= distance_of_time_in_words (Time.now, Time.local(1950,03,22)) %> old.
    

    produce

    Jack is 60 years old
    
    0 讨论(0)
提交回复
热议问题