我有一个带有date列的模型birthday

我如何计算直到用户下一个生日的天数?

最佳答案

这里有一个简单的方法。你要确保捕获今年已经通过的案例(以及尚未通过的案例)

class User < ActiveRecord::Base
  attr_accessible :birthday

  def days_until_birthday
    bday = Date.new(Date.today.year, birthday.month, birthday.day)
    bday += 1.year if Date.today >= bday
    (bday - Date.today).to_i
  end
end

并证明这一点! (我添加的是 timecop gem 以保持今天的计算准确(2012-10-16)
require 'test_helper'

class UserTest < ActiveSupport::TestCase

  setup do
    Timecop.travel("2012-10-16".to_date)
  end

  teardown do
    Timecop.return
  end

  test "already passed" do
    user = User.new birthday: "1978-08-24"
    assert_equal 313, user.days_until_birthday
  end

  test "coming soon" do
    user = User.new birthday: "1978-10-31"
    assert_equal 16, user.days_until_birthday
  end
end

关于ruby-on-rails - 在 Rails 中计算距下一个生日的天数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12926126/

10-11 10:27