Generates fake dates and times, formatted as human-readable date-time strings(DD-MM-YYYY:HH24:MM:SS in Oracle's date format); I needed a bunch of sample data to test a database application. You may need to generate old tax records or whatnot (warning: this code not guaranteed to save you from audits). Does no error checking, but should handle leap years nicely.

A tip of the hat to OeufMayo, who suggested a *nix timestamp (which limits the usefulness a bit, but not that much).

Combine it with Time::Local and timelocal to generate formatted time strings that lie between two dates.

sub fakedate { my ($lower_bound, $upper_bound) = @_; my $timestamp = $lower_bound + int rand ($upper_bound - $lower_bo +und +1); my @bits = (localtime($timestamp))[0..5]; $bits[5]+=1900; # year $bits[4]++; #month comes back as 0-11 sprintf("%02d-%02d-%4d:%02d:%02d:%02d", @bits[3,4,5,2,1,0]); }

Replies are listed 'Best First'.
Re: Generate Fake dates
by marcink (Monk) on Jun 27, 2001 at 01:05 UTC
    An alternative, lazy approach would be to use Date::Manip. It makes formatting a little easier:

    use Date::Manip; sub fakedate { my ($lower_bound, $upper_bound) = @_; my $timestamp = $lower_bound + int (rand $upper_bound - $lower_bo +und +1); return UnixDate( "epoch $timestamp", "%d-%m-%Y %H:%M:%S" ); }


    Update: okay, I just learned another thing: Date::Manip is slow. Very ;-) I used Benchmark to compare arturo's fakedate with mine:

    Benchmark: timing 1000 iterations of fakedate_a, fakedate_mk...
    fakedate_a:  0 wallclock secs ( 0.03 usr +  0.00 sys =  0.03 CPU) @ 33333.33/s (n=1000)
                (warning: too few iterations for a reliable count)
    fakedate_mk: 13 wallclock secs (12.76 usr +  0.09 sys = 12.85 CPU) @ 77.82/s (n=1000)
    

    Thanks to arturo and OeufMayo for pointing this.

    -marcink