Как получить день года в рубине?
Каков наилучший способ получить день года для любой конкретной даты в Ruby?
Например: 31/dec/2009
должен возвращать day 365
, а 01/feb/2008
должен возвращать day 32
Ответы
Ответ 1
В основном (показано здесь в irb):
>> require 'date'
>> Date.today.to_s
=> "2009-11-19"
>> Date.today.yday()
=> 323
Для любой даты:
>> Date.new(y=2009,m=12,d=31).yday
=> 365
Или:
>> Date.new(2012,12,31).yday
=> 366
@see также: Ruby Документация
Ответ 2
Используйте Date.new(year, month, day)
для создания объекта Date
для нужной даты, затем получите день года с yday
:
>> require 'date'
=> true
>> Date.new(2009,12,31).yday
=> 365
>> Date.new(2009,2,1).yday
=> 32
Ответ 3
Date#yday
- это то, что вы ищете.
Вот пример:
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
Ответ 4
вы могли бы что-то сделать с помощью civil_to_jd (y, m, d, sg = GREGORIAN)
из
http://ruby-doc.org/core/classes/Date.html