LoginSignup
2
4

More than 5 years have passed since last update.

Ruby で指定した年の日付の一覧を取得する

Last updated at Posted at 2017-05-21

サンプルコード

1月1日から12月31日までの Date オブジェクトを生成して、年月日と曜日を出力する。

require 'date'

def print_dates(year)
  dates = (Date.new(year, 1, 1)...Date.new(year + 1, 1, 1)).to_a
  puts "The year #{year} has #{dates.size} dates."
  dates.each do |d|
    puts d.strftime('%Y-%m-%d %a')
  end
end

print_dates(2000)
print_dates(2001)

以下に出力結果の一部を記す。

2000年は閏年なので366日。2月29日が存在する。

The year 2000 has 366 dates.
2000-01-01 Sat
2000-01-02 Sun
2000-01-03 Mon
2000-01-04 Tue
(略)
2000-02-28 Mon
2000-02-29 Tue
2000-03-01 Wed

2001年は閏年ではないので365日。2月29日は存在しない。

The year 2001 has 365 dates.
2001-01-01 Mon
2001-01-02 Tue
2001-01-03 Wed
2001-01-04 Thu
(略)
2001-02-28 Wed
2001-03-01 Thu

参考資料

2
4
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
2
4