Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate days until next birthday in Rails

I have a model with a date column called birthday.

How would I calculate the number of days until the user's next birthday?

like image 437
Kyle Decot Avatar asked Oct 17 '12 02:10

Kyle Decot


2 Answers

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
like image 94
Jesse Wolgamott Avatar answered Nov 04 '22 01:11

Jesse Wolgamott


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")
like image 21
unnitallman Avatar answered Nov 03 '22 23:11

unnitallman