我需要生成一个随机日期.我的计算时间不需要时间.我想要使用的是:
def date_rand from = 0.0, to = Time.now
Time.at(from + rand * (to.to_f - from.to_f))
end
Run Code Online (Sandbox Code Playgroud)
这让我很接近,但有一堆我不需要的其他信息.(时间,区域等)如果有办法在没有所有其他数据的情况下获取日期,我将非常感谢您对它的了解.
在Ruby 1.9中,包括date库在内的类中添加了一个#to_date方法Time(以及一个#to_datetime方法).Ruby 1.8也有它,但它是一个私有方法.
require 'date'
def date_rand(from = 0.0, to = Time.now)
Time.at(from + rand * (to.to_f - from.to_f)).to_date
end
Run Code Online (Sandbox Code Playgroud)
在Ruby 1.8中,你可以这样做:
def date_rand(from = 0.0, to = Time.now)
time = Time.at(from + rand * (to.to_f - from.to_f))
Date.civil(time.year, time.month, time.day)
end
Run Code Online (Sandbox Code Playgroud)