Reputation: 18348
$fromDateTS = strtotime($start_date);
$toDateTS = strtotime($end_date);
for ($currentDateTS = $fromDateTS; $currentDateTS <= $toDateTS; $currentDateTS += (60 * 60 * 24))
{
$currentDateStr = date("Y-m-d",$currentDateTS);
}
How would I convert this php to ruby. There doesn't seem to be a for loop in ruby that is similar to php
Upvotes: 0
Views: 1919
Reputation: 18775
I would code it this way:
from_start_date_ts = start_date.to_date
to_date_ts = end_date.to_date
from_start_date_ts.step(to_date_ts, 1.day).to_a.map{ |step_date| current_date_str = step_date.to_s }
This gives you back an array of step_date strings.
Upvotes: 1
Reputation: 30415
There are many solutions for this. You can do this for instance:
from_start_date_ts = Time.parse(start_date)
to_date_ts = Time.parse(end_date)
current_date_ts = from_start_date_ts
while current_date_ts < to_date_ts
current_date_ts += 1.day
current_date_str = current_date_ts.strftime("%D")
end
I haven't tested it so it might not work as it is but it is more to show you one possible syntax for a loop in Ruby. Note that you can use while in different ways:
while [condition]
# do something
end
begin
# do something
end while [condition]
You can also use the loop syntax:
loop do
# do something
break if [condition]
end
Or the until loop:
until current_date_ts > to_date_ts
current_date_ts += 1.day
current_date_str = current_date_ts.strftime("%D")
end
There are more :)
Upvotes: 1