Skip to content

Instantly share code, notes, and snippets.

@hara-y-u
Created January 10, 2025 05:15
Show Gist options
  • Save hara-y-u/5201c5439f687fd83f41516ca8c1a30f to your computer and use it in GitHub Desktop.
Save hara-y-u/5201c5439f687fd83f41516ca8c1a30f to your computer and use it in GitHub Desktop.
Calculate week index in month / Rubyで特定日が何番目の週か計算
require "date"
# Days from day one to first saturday are result in index 1
def week_index_in_month(date)
first_day_of_month = Date.new(date.year, date.month, 1)
((date.day + first_day_of_month.wday) / 7.0).ceil
end
# Days from day one to seven are result in index 1
def week_index_in_month(date)
(date.day / 7.0).ceil
end
@hara-y-u
Copy link
Author

hara-y-u commented Jan 10, 2025

月の中での何番目かを計算するにはシンプルに7で割って整数に切り上げれば良い(0始まりとするには切り下げ)。
第一週の土曜より後を第二週として計算するにはその月の1日のwdayを足してから7で割ると良い。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment