Ruby 我需要生成一个随机日期,MM/DD/YYYY
我需要生成一个随机日期。 我不需要时间来计算。 我想用的是:Ruby 我需要生成一个随机日期,MM/DD/YYYY,ruby,Ruby,我需要生成一个随机日期。 我不需要时间来计算。 我想用的是: def date_rand from = 0.0, to = Time.now Time.at(from + rand * (to.to_f - from.to_f)) end 这让我很接近,但有一大堆其他我不需要的信息。(时间、区域等) 如果有一种方法可以在不使用所有其他数据的情况下获取日期,我将非常感谢您的帮助。在Ruby 1.9中,包括date库,在Time类中添加了\to\u date方法(以及\to\u datetim
def date_rand from = 0.0, to = Time.now
Time.at(from + rand * (to.to_f - from.to_f))
end
这让我很接近,但有一大堆其他我不需要的信息。(时间、区域等)
如果有一种方法可以在不使用所有其他数据的情况下获取日期,我将非常感谢您的帮助。在Ruby 1.9中,包括
date
库,在Time
类中添加了\to\u date
方法(以及\to\u 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
在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
来自欧比·费尔南德斯的一封信
class Time
def self.random(years_back=5)
year = Time.now.year - rand(years_back) - 1
month = rand(12) + 1
day = rand(31) + 1
Time.local(year, month, day)
end
end
这允许您调用Time.random。我将此作为对您问题的另一种回答,并根据您打算如何使用此选项,请小心,因为如果有一天其他人不得不调试/支持您的代码,那么猴子修补标准库类通常不是最好的方法。dmarkov的回答很好。您可以对日期执行相同的操作:
require 'date'
def date_rand(from = Date.new(1970,1,1), to = Date.today)
low, high = from.ajd.to_i, to.ajd.to_i
r = rand(high-low+1) + low
Date.jd(r)
end
所以我使用的是Ruby 1.8版本,它工作得很好!!!但是,我需要能够更改它的格式。我得到“1979-02-19”,但我需要“02-19-1979”。如果你知道一个快速的方法来做到这一点,将不胜感激。再次感谢您的帮助。这两种方法都返回一个
Date
对象。对日期
对象调用到
默认为YYYY-MM-DD
格式。您可以改用strftime:date\u rand.strftime(“%m-%d-%Y”)