0
    $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

2 Answers 2

1

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 :)

Sign up to request clarification or add additional context in comments.

2 Comments

You could also do "current_date_ts += 1.day" and use "current_date_ts.strftime(format string)" to format it as well :)
while you're at it, don't forget about the "until" loop... just 'cause it reads so nice
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.