7

我有一个模型,其date列名为birthday.

我将如何计算距离用户下一个生日的天数?

4

4 回答 4

15

这是一个简单的方法。您需要确保抓住今年已经通过的案例(以及尚未通过的案例)

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
于 2012-10-17T03:00:20.033 回答
2

试试这个

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")
于 2012-10-17T05:34:42.967 回答
0

对此进行滑动:

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 是否为您提供了任何使这更容易的东西。

于 2012-10-17T03:03:19.887 回答
0

这是另一种使用鲜为人知的方法来解决此问题的方法,但它们使代码更加不言自明。此外,这适用于 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
于 2020-07-14T14:43:43.060 回答