How to Obtain a Random Time for a Day Specified in ruby

Asked 2 years ago, Updated 2 years ago, 49 views

How do I get a Time object with a random time by specifying only the date in ruby?

For example, if you want a random date of 'June 22, 2016',
June 22, 2016 19:44:34.

ruby-on-rails ruby

2022-09-30 20:19

2 Answers

How about adding a random number less than 24*60*60 seconds per day to that date?

r=Random.new
day = Time.local (2016, 6, 22, 0, 0, 0) + r.rand (24*60*60)
=>2016-06-22 13:54:03+0900


2022-09-30 20:19

defland_str
  num=(0...60).to_a.sample
  num<10?"0#{num}":num.to_s
end

puts "June 22, 2016 #{land_str}:#{land_str}:#{land_str}"


2022-09-30 20:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.