7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby/Railsで月の何週目、何曜日から日付を求める

7
Last updated at Posted at 2018-02-02
lib/date_helper.rb
require 'date'
require 'active_support'
require 'active_support/core_ext/date'

class Date
  def date_from_week_and_day(week, wday)
    # 当月の初日を出す
    d = beginning_of_month
    # 初週の日数
    first_week = 7 - d.wday

    day = first_week + (7*(week-2)) + wday + 1  # 日曜始まりにするためにwday+1にする
		
    # その月に存在しない日になったらfalse
    return false if end_of_month.day < day || day < 1
    Date.new(year, month, day)
  end
end

使い方

require 'date_helper'

d = Date.today
# => Fri, 02 Feb 2018

# 今月の3週目火曜日(wday=2)の日にち
d.date_from_week_and_day(3,2)
# => Tue, 13 Feb 2018

日付から何週目、何曜日を求めたいとき

こちらが参考になりました。多謝。
https://gist.github.com/komiya-atsushi/3269033

7
5
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
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?