Follow Along as I Stumble on the Path to Learning RoR

Posts tagged “date

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


Common Formatting Helpers

Adding  a list of some of the Rails formatting helpers I often have to use:

  • Converting a number to a dollar amount -> number_to_currency(field_value)
  • Changing the date to US date format (MM/DD/YYYY) -> field_value.strftime(“%m/%d/%Y”)
  • Converting to a percentage -> number_to_percentage(field_value)

For additional helpers with numbers here’s the link to the Rails API for number helpers


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 


Formatting Date Display in Rails

I needed help in formatting time in Rails and found here in the strftime( string ) → string section.  In particular, I wanted to change the default timestamp (created_at) to an American format MM/DD/YYYY.

http://www.ruby-doc.org/core-1.9.3/Time.html#M000297

 


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!


US Date Format

My dates were displaying DD-MM-YYYY, but I wanted to display it MM/DD/YYYY.

Here’s an easy way to do that.

http://www.spritle.com/blogs/?p=174