Ruby on rails 获取Rails中特定时间之间的随机时间对象

Ruby on rails 获取Rails中特定时间之间的随机时间对象,ruby-on-rails,ruby,datetime,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 objec

我想要一种方法:

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.?

这是第一次尝试:

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

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

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

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

至于为时间创建DSL。你可以看看Rails是如何做到这一点的。但是要得到你想要的东西。只需创建一个表示一天中小时数的类。用Fixnum上的am或pm调用实例化它。然后为今天的_的(以及您想要的任何其他方法)编写方法

您应该添加一些24小时以上的错误处理。

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)

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

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')

你所说的
毫秒秒
,是指
秒(分钟
)吗?
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')