Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Array of Days Between Two Dates

Tags:

ruby

I would like to list an array of days between two dates. I can list an array of months with the code below. How might I change this to show every day between two dates?

require 'date'

date_from  = Date.parse('2011-05-14')
date_to    = Date.parse('2011-05-30')
date_range = date_from..date_to

date_months = date_range.map {|d| Date.new(d.year, d.month, 1) }.uniq
date_months.map {|d| d.strftime "%d/%m/%Y" }

puts date_months
like image 406
Brandon Avatar asked Sep 27 '14 06:09

Brandon


1 Answers

I don't know which day you meant, thus I have shown all the ways.

#wday is the day of week (0-6, Sunday is zero).

 (date_from..date_to).map(&:wday)

#mday is the day of the month (1-31).

(date_from..date_to).map(&:mday)

#yday is the day of the year (1-366).

(date_from..date_to).map(&:yday)

OP's actual need was not much clear to me. After few comments between us, I came to know from OP's comment, the below answer OP is looking for -

(date_from..date_to).map(&:to_s)
like image 160
Arup Rakshit Avatar answered Sep 21 '22 06:09

Arup Rakshit