Created
January 10, 2025 05:15
-
-
Save hara-y-u/5201c5439f687fd83f41516ca8c1a30f to your computer and use it in GitHub Desktop.
Calculate week index in month / Rubyで特定日が何番目の週か計算
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
月の中での何番目かを計算するにはシンプルに7で割って整数に切り上げれば良い(0始まりとするには切り下げ)。
第一週の土曜より後を第二週として計算するにはその月の1日のwdayを足してから7で割ると良い。