Setting a Variable to a Specific Date

If you need to set a variable to a specific date, the way to do it is to use the Date.new method.

Date.new(year, month, day)

For example:

foo = Date.new(2013, 8, 31)

Advertisements

Changing the Date from UTC to Another Time Zone

I had some calculations that I wanted to do according to my app’s time zone and not UTC.  Date.today was changing earlier than I wanted it to since the default is to use UTC.  However, I found a simple way to fix this:

in application.rb:

config.time_zone = ‘Eastern Time (US & Canada)’

then you can use this to get the date in the time zone you set:

Time.current.to_date

If do not want to set the time_zone in the configuration, you can just do this:

Time.now.in_time_zone( ‘Eastern Time (US & Canada)’).to_date

Accepting American Date Format

I needed code to allow users to enter dates in American format MM/DD/YYYY, and for it to save correctly in my database.  Previously, I was using American Date Monkey Patch code (http://stackoverflow.com/questions/6825048/how-to-make-assigning-an-american-formatted-date-string-into-a-date-variable-wor), but I started having issues with it.

So I moved to this gem by Jeremy Evans that does the same, The Ruby American Date Gem:

https://github.com/jeremyevans/ruby-american_date 

Validations for Dates

I searched many times trying to figure out how to validate date of birth in my user model.  Finally, I stumbled on the validates_timeliness gem and it worked great for validating if a user was old enough to join my site.

after installing the gem, i just added the line from the example in my user model:

validates_date :date_of_birth, :before => lambda { 18.years.ago },
                              :before_message => "must be at least 18 years old"

https://github.com/adzap/validates_timeliness

Thank you for making this gem available adzap!