Ruby: how to find a date by the year day

Viewed 108

How is it possible to find the date based on the current year's day? For example, you have the year's day 235, which date does it corresponds to?

For example, you can find a year's day as follows:

Date.today.yday
#=> 126 (for May 6, 2021)

How to achieve the opposite?

Date.some_method(126)
#=> 2021-05-06

I tried as follows:

now = Date.today
#=> Thu, 06 May 2021
start_year = now.beginning_of_year
#=> Fri, 01 Jan 2021 

start.advance(days: (start.yday + 126))
#=> Sat, 08 May 2021 

Why there is a difference of 2 days?

3 Answers

This should work (pure ruby):

def day_of_year(num)
  Date.new(Date.today.year) + num - 1
end

day_of_year(1) #=> 01/01/2021
day_of_year(235) #=> 23/08/2021

Another option:

def day_of_year(num)
  Date.strptime(num.to_s, "%j")
end

day_of_year(1) #=> 01/01/2021
day_of_year(235) #=> 23/08/2021

Note: @steenslag posted the actually correct answer - please go and upvote.

Date.ordinal gives you the date, given the year and the number. You can even specify a negative number, which would calculate the date counting backwards from the end of the year. doc

Try This.

Date.today - (Date.today.yday - 126)

Related