Posted By

vanne on 07/25/07


Tagged

ruby


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

basicmagic


random date


 / Published in: Other
 

  1. # generates a random date
  2. # you can simply call it like random_date to generate a simple random date
  3. # otherwise you can pass hash values to generate like
  4. # random_date :year => your_year, :month => range_of_month,
  5. # :day => range_of_days, :format => format_string (same as Date#strftime)
  6. # :return_date => true/false (will return a date object if true)
  7. def random_date(options={})
  8. options[:year] ||= Time.now.year
  9. options[:month] ||= rand(12)
  10. options[:day] ||= rand(31)
  11. options[:format] ||= "%Y-%m-%d"
  12. options[:return_date] ||= false
  13.  
  14. str = "#{options[:year]}-#{options[:month]}-#{options[:day]}".to_date.strftime options[:format]
  15. date = "#{options[:year]}-#{options[:month]}-#{options[:day]}".to_date
  16.  
  17. options[:return_date] ? date : str
  18. # if the date is invalid let's re-try we'll probably get a valid date the next time around
  19. # we're passing format because the format needs to stay consistent
  20. rescue ArgumentError
  21. random_date :format => options[:format]
  22. end

Report this snippet  

You need to login to post a comment.