Calculate days until next birthday in Rails

Here's a simple way. You'll want to make sure to catch the case where it's already passed this year (and also the one where it hasn't passed yet)

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

And to prove it! (all I've added is the timecop gem to keep the calculations accurate as of today (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

Try this

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")