[英]Convert PHP to Ruby (On Rails)
$fromDateTS = strtotime($start_date);
$toDateTS = strtotime($end_date);
for ($currentDateTS = $fromDateTS; $currentDateTS <= $toDateTS; $currentDateTS += (60 * 60 * 24))
{
$currentDateStr = date("Y-m-d",$currentDateTS);
}
我怎么把這個PHP轉換為ruby。 在ruby中似乎沒有類似於php的for循環
有很多解決方案。 你可以這樣做:
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
我沒有對它進行測試,因此可能無法正常工作,但更多的是向您展示Ruby中循環的一種可能語法。 請注意,您可以以不同方式使用while:
while [condition]
# do something
end
begin
# do something
end while [condition]
您還可以使用循環語法:
loop do
# do something
break if [condition]
end
或者直到循環:
until current_date_ts > to_date_ts
current_date_ts += 1.day
current_date_str = current_date_ts.strftime("%D")
end
還有更多:)
我會這樣編碼:
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 }
這會返回一個step_date字符串數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.