How to get the day of year in ruby?
What is the best way to get the day of the year for an开发者_StackOverflowy specific date in Ruby?
For example: 31/dec/2009
should return day 365
, and 01/feb/2008
should return day 32
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
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
You can use time without importing anything:
Time.new(1989,11,30).yday
or for now:
Time.now.yday
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
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
精彩评论