23

What is the best way to get the day of the year for any specific date in Ruby?

For example: 31/dec/2009 should return day 365, and 01/feb/2008 should return day 32

wattostudios
  • 8,666
  • 13
  • 43
  • 57
Daniel Cukier
  • 11,502
  • 15
  • 68
  • 123

5 Answers5

71

Basically (shown here in irb):

>> require 'date'

>> Date.today.to_s
=> "2009-11-19"

>> Date.today.yday()
=> 323

For any date:

>> Date.new(y=2009,m=12,d=31).yday
=> 365

Or:

>> Date.new(2012,12,31).yday
=> 366

@see also: Ruby Documentation

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
miku
  • 181,842
  • 47
  • 306
  • 310
  • 1
    Cool that you show that yday is not great for comparison across leap years after February :) – toxaq Mar 18 '15 at 10:48
3

Use Date.new(year, month, day) to create a Date object for the date you need, then get the day of the year with yday:

>> require 'date'
=> true
>> Date.new(2009,12,31).yday
=> 365
>> Date.new(2009,2,1).yday
=> 32
Pär Wieslander
  • 28,374
  • 7
  • 55
  • 54
1

Date#yday is what you are looking for.

Here's an example:

require 'date'

require 'test/unit'
class TestDateYday < Test::Unit::TestCase
  def test_that_december_31st_of_2009_is_the_365th_day_of_the_year
    assert_equal 365, Date.civil(2009, 12, 31).yday
  end
  def test_that_february_1st_of_2008_is_the_32nd_day_of_the_year
    assert_equal 32, Date.civil(2008, 2, 1).yday
  end
  def test_that_march_1st_of_2008_is_the_61st_day_of_the_year
    assert_equal 61, Date.civil(2008, 3, 1).yday
  end
end
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
1

You can use time without importing anything:

Time.new(1989,11,30).yday

or for now:

Time.now.yday
bonafernando
  • 1,048
  • 12
  • 14
0

You might be able to do something with civil_to_jd(y, m, d, sg=GREGORIAN)

Cadoiz
  • 1,446
  • 21
  • 31
John Boker
  • 82,559
  • 17
  • 97
  • 130