数组中的日期范围,ruby
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4917827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Date range in an array, ruby
提问by Elliot
I was wondering how I can go about creating an arrary of the last month of days "Jan 21" style etc. automatically in ruby (in rails3)?
我想知道如何在 ruby 中(在 rails3 中)自动创建最后一个月“1 月 21 日”样式等的数组?
If today is Feb 6th, then the arrary would have ["Jan 6", "Jan 7"..."Feb 6"]
如果今天是 2 月 6 日,那么数组将有 ["Jan 6", "Jan 7"..."Feb 6"]
回答by Chubas
I don't know if I completely understood the question, but here's an answer that might help
我不知道我是否完全理解这个问题,但这里的答案可能会有所帮助
(1.month.ago.to_date..Date.today).map{ |date| date.strftime("%b %d") }
outputs
产出
["Jan 07", "Jan 08", "Jan 09", "Jan 10", "Jan 11", "Jan 12", "Jan 13", "Jan 14", "Jan 15", "Jan 16", "Jan 17", "Jan 18", "Jan 19", "Jan 20", "Jan 21", "Jan 22", "Jan 23", "Jan 24", "Jan 25", "Jan 26", "Jan 27", "Jan 28", "Jan 29", "Jan 30", "Jan 31", "Feb 01", "Feb 02", "Feb 03", "Feb 04", "Feb 05", "Feb 06"]
You can create a range of dates, and then convert them to the desired format using strftime
您可以创建一个日期范围,然后使用strftime将它们转换为所需的格式
Just make sure you use Dateobjects on your range instead of Timeobjects, otherwise you will create an array of every second included in that lapse.
只要确保使用Date范围内的Time对象而不是对象,否则您将创建一个包含在该间隔中的每一秒的数组。
回答by steenslag
require 'date'
now = Date.today
p (now<<1 .. now).map{ |day| day.strftime("%b %-e") }
# No railsy .month.ago.to_date silliness!
# the dash in `%-e` gets rid of the occasional extra space. Credit @Grizz in the comments.
Output:
输出:
["Jan 7", "Jan 8", "Jan 9", "Jan 10", (...), "Feb 7"]

