E
E
eldar_web2015-10-26 17:34:38
ruby
eldar_web, 2015-10-26 17:34:38

How can I get the difference in months from two dates in Ruby?

For example, there are variables:

start_date = '01.09.2015'
finish_date = '01.02.2016'


At the output, I want to get the following data (in an array):
09.2015
10.2015
11.2015
12.2015
01.2016
02.2016

How can I find a solution?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
N. Bekseitov, 2015-10-27
@eldar_web

I'll put in my 5 cents

require 'date'
start = Date.parse('2012-09-02')
finish = Date.parse('2013-11-02')
date_months = (start..finish).map {|d| Date.new(d.year, d.month) }.uniq
date_months.map {|d| d.strftime "%m/%Y" }

Result
["09/2012", "10/2012", "11/2012", "12/2012", "01/2013", "02/2013", "03/2013", "04/2013", "05/2013", "06/2013", "07/2013", "08/2013", "09/2013", "10/2013", "11/2013"]

E
Evgeny Tkachenko, 2015-10-26
@eugene20tkachenko

Easy:

require 'date'
start = Date.parse('2012-09-02')
finish = Date.parse('2013-11-30')
dates_array = (start..finish).map(&:to_s)

last line default Array

T
thepry, 2015-10-26
@thepry

finish = Date.parse('2015-09-02').beginning_of_month
start = Date.parse('2012-11-30').beginning_of_month
[].tap do |arr|
    while start <= finish do
        arr << start
        start += 1.month        
    end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question