Garbela
Garbela

Reputation: 73

How to get user's birthday based on day and month only

I want to have a member list for today's birthday and upcoming birthday(tommorow).

In users.controller.rb
def birthday
   @birthday_users = User.all.order("created_at DESC").where(:birthday => Date.today)
end

def upcoming_birthday
   @upcoming_birthday_user = User.all.order("created_at DESC").where(:birthday => 1.days.from_now )
end

These codes work only when the day, month and year are the same as today.

Example:

User 1's birthday = October 3 2018 (Showing on the birthday list)

User 2's birthday = October 3 2000 (Not showing on the birthday list)

Upvotes: 4

Views: 1476

Answers (2)

Anand
Anand

Reputation: 6531

In User model

PostgreSql

scope :today_birthday, { where('EXTRACT(month FROM birthday) = ? AND EXTRACT(day FROM birthday) = ?', Date.today.month, Date.today.day).order("created_at DESC") }

scope :upcoming_birthday, { where('EXTRACT(month FROM birthday) = ? AND EXTRACT(day FROM birthday) = ?', 1.days.from_now.month, 1.days.from_now.day).order("created_at DESC") }

MySql

scope :today_birthday, { where('MONTH(birthday) = ? AND DAY(birthday) = ?', Date.today.month, Date.today.day).order("created_at DESC") }

scope :upcoming_birthday, { where('MONTH(birthday) = ? AND DAY(birthday) = ?', 1.days.from_now.month, 1.days.from_now.day).order("created_at DESC") }

Upvotes: 5

Abhilash Reddy
Abhilash Reddy

Reputation: 1549

I'm assuming you want to find all users having a birthday today. So, you might want to ignore year and only consider month and day while querying. The below code might help you with that:

def birthday
  @birthday_users = User.where('EXTRACT(month FROM birthday) = ? AND EXTRACT(day FROM birthday) = ?', Date.today.strftime("%m"), Date.today.strftime("%d"))
end

def upcoming_birthday
  tomorrow = Date.today + 1.day
  @upcoming_birthday_users = User.where('EXTRACT(month FROM birthday) = ? AND EXTRACT(day FROM birthday) = ?', tomorrow.strftime("%m"), tomorrow.strftime("%d"))
end

Upvotes: 0

Related Questions