views:

118

answers:

4

What is the best way to get the day of year of an specific date in Ruby? For example: 31/dec/2009 -> 365, 01/feb/2008 -> 32, etc

A: 

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

from

http://ruby-doc.org/core/classes/Date.html

John Boker
+11  A: 

Basically (shown here in irb):

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

The MYYN
+1  A: 

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
A: 

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