在 Rails 中计算距离下一个生日的天数



我有一个模型,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

并证明这一点!(我添加的只是时间警察宝石,以保持今天的计算准确 (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

试试这个

require 'date'
def days_to_next_bday(bday)
  d = Date.parse(bday)
  next_year = Date.today.year + 1
  next_bday = "#{d.day}-#{d.month}-#{next_year}"
 (Date.parse(next_bday) - Date.today).to_i
end
puts days_to_next_bday("26-3-1985")
滑动

一下:

require 'date'
bday = Date.new(1973,10,8)  // substitute your records date here.
this_year  = Date.new(Date.today.year,   bday.month, bday.day )
if this_year > Date.today 
  puts this_year - Date.today
else
   puts Date.new(Date.today.year + 1,   bday.month, bday.day ) - Date.today
end

我不确定Rails是否给了你任何让你更容易的东西。

这是使用鲜为人知的方法解决此问题的另一种方法,但它们使代码更加不言自明。此外,这适用于 2 月 29 日的出生日期。

class User < ActiveRecord::Base
  attr_accessible :birthday
  def next_birthday
    options = { year: Date.today.year }
    if birthday.month == 2 && birthday.day == 29 && !Date.leap?(Date.today.year)
      options[:day] = 28
    end
    birthday.change(options).tap do |next_birthday|
      next_birthday.advance(years: 1) if next_birthday.past?
    end
  end
end

当然,距离下一个生日的天数是:

(user.next_birthday - Date.today).to_i

最新更新