在Rails中的某些小时之间获取随机时间对象

时间:2013-01-01 03:54:01

标签: ruby-on-rails ruby datetime

我想要一种方法:

def time_between(from, to)
  ***
end

time_between 10.am.of_today, 3.pm.of_today # => 1pm Time object
time_between 10.am.of_today, 3.pm.of_today # => 3pm Time object
time_between 10.am.of_today, 3.pm.of_today # => 10:30am Time object
# I mean random

这里有两个问题:如何实施***?以及如何实施x.pm.of_today

4 个答案:

答案 0 :(得分:8)

ruby​​ 1.9.3

require 'rubygems'
require 'active_support/all'

def random_hour(from, to)
  (Date.today + rand(from..to).hour + rand(0..60).minutes).to_datetime
end

puts random_hour(10, 15)

答案 1 :(得分:0)

这是第一次尝试:

def time_between(from, to)
  today = Date.today.beginning_of_day
  (today + from.hours)..(today + to.hours).to_a.sample
end

虽然它的作用如下:

time_between(10, 15) # => a random time between 10 am and 3 pm

我认为已经足够了,但我愿意接受更好的解决方案。

答案 2 :(得分:0)

要获得随机时间段,您需要计算两次之间的距离。获取该距离跨度的随机值。最后将它添加到您的时间。

类似的东西:(但我不打算测试它)

def time_between(from, to)
  if from > to
    time_between(to, from)
  else
    from + rand(to - from)
  end
end

至于时间创建DSL。你可以看看Rails是如何做到的。但要得到像你想要的东西。只需创建一个代表当天小时数的课程。使用Fixnum上的am或pm调用实例化它。然后为of_today(以及您想要的任何其他人)编写方法。

class Fixnum
  def am
    TimeWriter.new(self)
  end

  def pm
    TimeWriter.new(self + 12)
  end
end

class TimeWriter
  MINUTES_IN_HOUR = 60
  SECONDS_IN_MINUTE = 60
  SECONDS_IN_HOUR = MINUTES_IN_HOUR * SECONDS_IN_MINUTE

  def initialize hours
    @hours = hours
  end

  def of_today
    start_of_today + (hours * SECONDS_IN_HOUR)
  end

  private

  attr_reader :hours

  def start_of_today
    now = Time.now
    Time.new(now.year, now.month, now.day, 0, 0)
  end
end

您应该在超过24小时内添加一些错误处理。

答案 3 :(得分:0)

此代码将分钟和小时视为输入。

require 'rubygems'
require 'active_support/all'

def random_time(from, to)
  from_arr = from.split(':')
  to_arr   = to.split(':')
  now      = Time.now
  rand(Time.new(now.year, now.month, now.day, from_arr[0], rom_arr[1])..Time.new(now.year, now.month, now.day, to_arr[0], to_arr[1]))
end

puts random_time('09:15', '18:45')

另一种做同样的简短方法:

require 'rubygems'
require 'active_support/all'

def random_time(from, to)
  now      = Time.now
  rand(Time.parse(now.strftime("%Y-%m-%dT#{from}:00%z"))..Time.parse(now.strftime("%Y-%m-%dT#{to}:00%z")))
end

puts random_time('09:15', '18:45')