Daniel Cukier
Daniel Cukier

Reputation: 11942

How to get the day of year in ruby?

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

Upvotes: 26

Views: 17761

Answers (5)

John Boker
John Boker

Reputation: 83699

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

Upvotes: 0

bonafernando
bonafernando

Reputation: 1149

You can use time without importing anything:

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

or for now:

Time.now.yday

Upvotes: 1

miku
miku

Reputation: 188004

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

Upvotes: 74

Jörg W Mittag
Jörg W Mittag

Reputation: 369428

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

Upvotes: 1

P&#228;r Wieslander
P&#228;r Wieslander

Reputation: 28934

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

Upvotes: 3

Related Questions