jsnow
jsnow

Reputation: 163

string in ddmmyyyy format to to date

I have a folder that contains a bunch of folders all with the naming convention of mmddyyyy (for example 04102013, 04092013, etc.). I have a text file that contains all these paths and have successfully programed in Ruby an array that strips out the path so we are left with just the date (however I believe it is stored as a sting).

What I need to do now is take the dates in the array and add an amount of days to them. The amount of days will be static and the same value needs to be applied across the board for everything in the array. On the 8th line I am getting an invalid date (ArgumentError). The end result needs to be an array with +7 days to every item in the array. Right now I can't even get the values into a date format.

require 'date'
myarray = IO.readlines "/path/to/myfile.txt"
myarray.each do |s|
  s.gsub!('/path/to/my/dated/folders/', '')
end
print myarray 

myarray.map! {Date.strptime("%m%d%Y")}
# myarray.map! {+(7)}
print myarray

Upvotes: 0

Views: 117

Answers (2)

lightswitch05
lightswitch05

Reputation: 9428

You are very close! You need to pass your array value to the date constructor.

myarray.map!{|date| Date::strptime(date, "%m%d%Y") + 7}

Upvotes: 0

Philip Hallstrom
Philip Hallstrom

Reputation: 19899

Try:

myarray.map!{|s| Date.strptime(s, '%m%d%Y') + 7}

Upvotes: 1

Related Questions