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

前端 未结 13 2208
被撕碎了的回忆
被撕碎了的回忆 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 17:02

    I came up with the following, based on a similar reasoning as @FMc First, compute the diff between today's year and birthday's year. Then, sum it to birthday and check the resulting date: if it's greater than today, decrease diff by 1. To be used in Rails apps as it relies on ActiveSupport's years method

    def age(birthday, today)
      diff = today.year - birthday.year
      (birthday + diff.years > today ) ? (diff - 1) : diff
    end
    

提交回复
热议问题