Get an array including every 14th day from a specific date

In ruby, how can I get every 14th day of the year going back and forth from the date.

So consider that I was billed for 2 weeks of recycling today, 6-16-2015. How can I get an array of each billing day for recycling this year based on that date.

+3


source to share


4 answers


Date has a step method :



require 'date'

d = Date.strptime("6-16-2015", '%m-%d-%Y') # strange date format
end_year = Date.new(d.year, -1, -1)
p d.step(end_year, 14).to_a

# =>[#<Date: 2015-06-16 ((2457190j,0s,0n),+0s,2299161j)>, #<Date: 2015-06-30 ((2457204j,0s,0n),+0s,2299161j)>, ...

# Going backward:
begin_year = Date.new(d.year, 1, 1)
p d.step(begin_year,-14).to_a

# =>[#<Date: 2015-06-16 ((2457190j,0s,0n),+0s,2299161j)>, #<Date: 2015-06-02 ((2457176j,0s,0n),+0s,2299161j)>,...

      

+5


source


You can do it like this:

require 'date'

date_str = "6-16-2015"

d = Date.strptime(date_str, '%m-%d-%Y')
f = Date.new(d.year)
((f + (f-d).abs % 14)..Date.new(d.year,-1,-1)).step(14).to_a
  #=> [#<Date: 2015-01-13 ((2457036j,0s,0n),+0s,2299161j)>,
  #    #<Date: 2015-01-27 ((2457050j,0s,0n),+0s,2299161j)>,
  #    ...
  #    #<Date: 2015-06-16 ((2457190j,0s,0n),+0s,2299161j)>,
  #    ...
  #    #<Date: 2015-12-29 ((2457386j,0s,0n),+0s,2299161j)>]

      



Based on the second sentence of your question, I am assuming that you just want an array of all dates in a given year that are two weeks apart and include the given day.

+1


source


More detailed and understandable solution:

    require 'date'
    current_date = Date.parse "16-june-15"
    start_date = Date.parse '1-jan-15'
    end_date = Date.parse '31-dec-15'
    interval = 14
    result = current_date.step(start_date, -interval).to_a
    result.sort!.pop
    result += current_date.step(end_date, interval).to_a

      

+1


source


I tried a math approach, which was unexpectedly confusing.

require 'date'

a_recycle_date_string = "6-17-2015"
interval = 14

a_recycle_date = Date.strptime(a_recycle_date_string, '%m-%d-%Y')
current_year = a_recycle_date.year
end_of_year = Date.new(current_year, -1, -1)

# Find out which index of the first interval days is the first recycle day 
# of the year the (1 indexed)
remainder = (a_recycle_date.yday) % interval
# => 0

# make sure remainder 0 is treated as interval-1 so it doesn't louse 
# the equation up
n_days_from_first_recycling_yday_of_year = (remainder - 1) % interval


first_recycle_date_this_year = Date.new(current_year, 
                                        1, 
                                        1 + n_days_from_first_recycling_yday_of_year)

first_recycle_date_this_year.step(end_of_year, interval).to_a

      

0


source







All Articles