Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# An extension to Ruby's Time class which allows random date and time generation. 
# Modified slightly from the Danish extension to faker (where this snippet can 
# also be found, at http://github.com/jesperronn/faker_extension_da/blob/master/lib/faker_da/time.rb)

class Time
  class << self
      require 'date'

      def random_date_for_month(month, year = Time.now.year)
        Date.new( year, month, random_day_of_month( year, month ) )
      end

      def random_time_for_date(year, month, day)
        Time.local( year, month, day, rand(24), rand(60), rand(60) )
      end

      def random_time_in_month(month, year = Time.now.year)
        Time.local( year, month, self.random_day_of_month( year, month ), rand(24), rand(60), rand(60) )
      end

      def days_in_month(year, month)
        (Date.new( year, 12, 31 ) << ( 12 - month )).day
      end

      def random_day_of_month(year, month)
        rand( days_in_month( year, month ) ) + 1
      end

      def random_day_of_year(year)
        random_date_for_month(random_month, year)
      end

      def random_month
        (1..12).to_a[rand(12)]
      end

      def random_date(first_year=1960, last_year=2000)
        random_day_of_year (first_year..last_year).to_a[rand(last_year-first_year)]
      end

      def random_date_and_time(first_year=1960, last_year=2000)
        day = Time.random_date(first_year, last_year); day_and_time = Time.random_time_for_date(day.year, day.month, day.day)
        day_and_time
      end 
    end
end

if __FILE__ == $0
  puts "100 random datetimes: "
  100.times do puts " * " + Time.random_date_and_time.to_s end
end