LoginSignup
4
1

More than 5 years have passed since last update.

プレミアムフライデーに備えよう!Railsで次の月末の金曜日を取得する!

Last updated at Posted at 2017-02-26

ちまたでプレミアムフライデーが話題になってたので、Railsでプレミアムフライデーの日付を取得するメソッドを作った。


def next_premium_friday
  now = DateTime.now
  premium_friday = this_month_premium_friday(now)
  if now > premium_friday
    premium_friday = this_month_premium_friday(now + 1.month)
  end
  premium_friday
end

# 指定された日付と同じ月の月末の金曜日を取得するメソッド
def self.this_month_premium_friday(datetime)
  end_of_month = datetime.end_of_month
  case end_of_month.wday
  when 0..4
    difference_wday = -2 - end_of_month.wday
  when 5..6
    difference_wday = 5 - end_of_month.wday
  end
  premium_friday = end_of_month + difference_wday.day
end
4
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1