1
0

More than 1 year has passed since last update.

【Ruby】Date で月末の日付を得る

Posted at

Ruby で,年と月が与えられてその月の月末の日付を得るにはどうするか。
言うまでもなく月末が何日かは月によって異なるし,2 月は年によっても異なる。

Date.new の仕様の基本を知っていれば簡単なのだが知らなかった(てへ)。

require "date" 

year = 2022
month = 2

puts Date.new(year, month, -1) # => 2022-02-28

「年・月・日」の「日」を指定する第三引数に負数を与えると,月末から数えた日と解釈されるのであった(-1 だと末日,-2 だとその前日,など)。

既に日付オブジェクトが与えられているときに,その月の末日を得るには

require "date"

date = Date.new(2022, 2, 14)

puts date.then{ Date.new(_1.year, _1.month, -1) }
# => 2022-02-28

みたいにして計算できる。

1
0
2

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
1
0